简体   繁体   English

检查用户输入是否是 C 中的 integer

[英]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.将检查输入是否为 integer。 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.将解析标准输入缓冲区中存在的stdin如果确实可解析,则不可解析的字符将保留在缓冲区中。

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.此代码中的技巧是在scanf之后检查缓冲区中存在的字符是否为换行符( \n ),如果是,则该值已正确解析,在这种情况下,请求新输入的循环将不会执行,如果没有,未解析的字符仍将在缓冲区中,将由getchar读取,这将验证它确实不是\n ,并且将执行循环。

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.这样做的问题是,如果您输入诸如"aadd"之类的内容,则循环将执行 4 次,即输入缓冲区中剩余的字符数。

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.尽管它或多或少有效,但它不是最好的方法,如评论中所述,最好使用fgets之类的内容从缓冲区中读取该行,例如使用sscanfstrtol对其进行解析,如果失败,请询问新的输入。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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