Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent users from inputting letters or numbers?

Tags:

c

scanf

I have a simple problem;

Here is the code :

#include<stdio.h>
main(){
 int input;
 printf("Choose a numeric value");
 scanf("%d",&input);
}

I want the user to only enter numbers ... So it has to be something like this :

#include<stdio.h>
main(){
 int input;
 printf("Choose a numeric value");
 do{
   scanf("%d",&input);
 }while(input!= 'something');
}

My problem is that I dont know what to replace in 'something' ... How can I prevent users from inputting alphabetic characters ?

EDIT

I just got something interesting :

#include<stdio.h>
main(){
 int input;
 printf("Choose a numeric value");
 do{
   scanf("%d",&input);
 }while(input!= 'int');
}

Adding 'int' will keep looping as long as I enter numbers, I tried 'char' but that didnt work .. surely there is something for alphabets right ? :S Please reply !

Thanks for your help !

like image 644
NLed Avatar asked Feb 27 '23 01:02

NLed


1 Answers

The strtol library function will convert a string representation of a number to its equivalent integer value, and will also set a pointer to the first character that does not match a valid number.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
...
int value;
char buffer[SOME_SIZE];
char *chk;
do 
{
  printf("Enter a number: ");
  fflush(stdout);
  if (fgets(buffer, sizeof buffer, stdin) != NULL)
  {
    value = (int) strtol(buffer, &chk, 10); /* assume decimal format */
  }
} while (!isspace(*chk) && *chk != 0);

If chk points to something other than whitespace or a string terminator (0), then the string was not a valid integer constant. For floating-point input, use strtod.

like image 176
John Bode Avatar answered Mar 07 '23 03:03

John Bode