简体   繁体   中英

check whether user input is an integer in C

I have read in an earlier discussion that

#include <stdio.h>

int main ()
{
    int num;

    printf("\nPlease enter an integer:\n");
    scanf("%d",&num);

//   Let us check whether the user input is in integer        //

    while ((num = getchar()) != '\n' && num != EOF)
    {
         printf("\n\nError in input\n");
         printf("Please enter valid integer\n");
         scanf("%d",&num);
    } 

}

will check whether the input is an integer or not. The code works. But I do not understand what

while ((num = getchar()) != '\n' && num != EOF)

is doing. Can anyone help?

scanf("%d",&num); will parse the integer present in stdin buffer if it is indeed parseable, characters that are not parseable will remain in the buffer.

The trick in this code is to check, after the scanf , if the character present in the buffer is a newline ( \n ), if it is, the value was parsed correctly, in that case the loop asking for new input will not be executed, if not, the non parsed character will still be in the buffer, will be read by getchar which will verify that indeed it's not \n , and the cycle will be executed.

The problem with this is that if you input something like "aadd" the cycle will execute 4 times , the number of characters that remained in the input buffer.

Though it, more or less works, it's not the best method, as stated in the comments, it's best to read the line from the buffer with something like fgets , parse it, for example, with sscanf or strtol and if it fails, ask for new input.

while ((num = getchar()) != '\n' && num != EOF)

is just a needlessly obfuscated way of writing:

num = getchar();
while((num != '\n') && (num != EOF)) // inner parenthesis not necessary, just for readability
{
  ...
  num = getchar();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM