Check if user input is a valid string or not using C

I am taking string input from the user. But how do I check if a user has entered a string or a number?

+2
source share
7 answers

Call strtol, make sure that the value stored in endptr is not equal to the input value (successful conversion) and is a pointer to a NUL byte (the entire string was used).

http://www.opengroup.org/onlinepubs/000095399/functions/strtol.html

explains that if you also want to detect overflow, the trick is to set errno to 0, then call strtol, and then check that errno is still 0.

, isspace(), . , strtol , , , "1" .

strtoll strtod , .

+7

, :

char c;
scanf( "%c", &c );
if( isdigit(c) )
  printf( "You entered the digit %c\n", c );
+2
int isNum;
 if ((isNum = strtol(string, NULL, 10)))
  printf(" '%d' numbers was found!\n", isNum);
else
 {
     printf("No number found");
 }

, , ZERO (0).

strtol() , , .

 int isNum
 isNum = atoi(string);
+2

.

, /, , , .

. . " ?". StackOverflow ... (, ).

+2

atoi atof, , , 0. , "0".

- , [0-9], +/- , .

+1

, "" . , . : , , , . , , (, , ).

sscanf .

, int, (long ..) . .

+1

Instead of using functions such as strtol, atoi, atof .. you can define your own function that analyzes the character by the character of the string and builds the output integer. If during this analysis, if the character is not a number, you can safely say that the string is in NaN. Or you can also use isdigit () and check for each character, and if all the characters are numbers, then convert the string to a number using atoi.

0
source

Source: https://habr.com/ru/post/1727710/


All Articles