How can I distinguish between integer and character when using scanf ()

I just use the scanf() function. Code below:

 scanf("%d",&a); printf("%d",a); 

When I enter 1, it prints 1 as I want. But even when I enter 1a, it prints 1, as before. when the user enters something non-integer ((ex) 2,3,12ab, 1 a) I want to show the user a warning as an "integer input".

How can I solve this problem?

+2
source share
1 answer

Read all of this in a line using fgets() .

If you just want all of them to go into one int , go isdigit() line and find isdigit() on each char, and then when you find that they are all just numbers, call strtod() if you don't get an error and repeat the request.

If you want several things to be parsed from the same input line, you need to parse the line with something like strtok() to get individual tokens one at a time, and then look at each token and determine if it is a number that each character isdigit() or equal to '-' '.' etc. If so, parse it as a number using strtol() or strtod() (etc.) (Depending on what you see, int or float / double). Otherwise, parse the token as a string or throw an error.

+3
source

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


All Articles