Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何验证输入类型以仅接收整数?_C_Validation - Fatal编程技术网

C 如何验证输入类型以仅接收整数?

C 如何验证输入类型以仅接收整数?,c,validation,C,Validation,我只想从用户那里接收integer,我试着按照下面的代码进行操作,但似乎不太正确 int num; printf("What is the ID?\n>> "); while(!scanf("%d", &num)){ // consume new line getchar(); printf("\nInvalid ID please try again...\n\n");

我只想从用户那里接收integer,我试着按照下面的代码进行操作,但似乎不太正确

int num;

printf("What is the ID?\n>> ");
        while(!scanf("%d", &num)){
            // consume new line
            getchar();
            printf("\nInvalid ID please try again...\n\n");
            printf("What is the ID?\n>> ");
        }
如果我只在
scanf
中输入
a
,它工作正常,但是当我在
scanf
中输入
ab
时,它会循环2次,如果我输入3个字母,它会循环3次。为什么

What is the ID?
>> a

Invalid ID please try again...

What is the ID?
>> abc

Invalid ID please try again...

What is the ID?
>>
Invalid ID please try again...

What is the ID?
>>
Invalid ID please try again...

What is the ID?
>>
#包括
内部主(空){
int-num;
字符c;
printf(“ID是什么?\n>>”;
而(!scanf(“%d”、&num)){
//消费新品
获取(&c);
printf(“\n无效ID请重试…\n\n”);
printf(“ID是什么?\n>>”;
}
返回0;
}

通过添加一个get(),您可以在新行中输入并删除该问题

代码需要使用非数字输入行

阅读该行其余部分的各种方法


避免在下面。如果下一个字符是
“\n”
,则无法读取任何内容

scanf("%*[^\n]%*c");

我意识到问题在于scanf之后的新线路。如果我只是在
scanf
之后写3
getchar()
,它工作得很好,但我相信应该有一个正确或更好的方法来做这件事?
getchar()
只消耗一个字符,您应该使用循环继续消耗字符,直到消耗了换行符(或EOF)。
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
  ;
}
scanf("%*[^\n]");  // read all non- \n
scanf("%*1[\n]");  // read 1 \n
scanf("%*[^\n]%*c");