我有以下代码行:
printf("enter a number: \n");
if (scanf("%d", &x) == 1)
{ //do some stuff}
else {return 1;}
printf("enter another number: \n");
if (scanf("%d",&y) == 1)
{ //do some stuff}
else {return 1;}
代码可以工作,但是当我以以下形式“1 1”(1然后空格然后再次1)将输入输入到x时,它将第二个1放入y中。我怎样才能让它不会发生?它应该只是停止代码。
我知道还有其他方法来获取输入,但目前,我只允许使用 scanf 来获取用户的输入。
最佳答案
您正在看到 scanf
的正常行为。第二个 1 被读取
第二个 scanf
因为 %d
会跳过空格,直到找到下一个数字
转换。
在第一个 scanf
之后,这是输入缓冲区中剩下的内容
+-----+-----+------+
| ' ' | '1' | '\n' |
+-----+-----+------+
所以如果你想在第一次转换后停止,你需要清除缓冲区。 您可以使用此功能来实现以下目的:
void clear_line(FILE *fp)
{
if(fp == NULL)
return;
int c;
while((c = fgetc(fp)) != '\n' && c != EOF);
}
然后你可以这样做:
printf("enter a number: \n");
if (scanf("%d", &x) == 1)
{ //do some stuff}
else {return 1;}
clear_line(stdin);
printf("enter another number: \n");
if (scanf("%d",&y) == 1)
{ //do some stuff}
else {return 1;}
clear_line(stdin);
在这种情况下,即使您输入 1 1
,第二个 scanf
也会等待用户
输入。
关于c - scanf 输入验证也 1 scanf 获取 2 个输入并将其发送到下一个 var 而无需,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49440729/