这是我在这里发表的第一篇文章,我对 C 语言还比较陌生(这只是我在 uni 上的第二个单元)。
基本上,我正在尝试编写一段代码,询问用户是否希望继续。如果他们写"is",代码将继续循环。如果他们写否,代码将终止程序。如果他们写了其他任何东西,它只会再次询问,直到有可识别的输入。我正在使用 scanf 和 printf,并尝试仅使用它们来创建此代码。
char userInput[4];
userInput[0] = '\0';
while ((strcmp(userInput, "yes") != 0) && (strcmp(userInput, "no") != 0))
{
printf("Do you want to continue (yes/no) :");
scanf("%3s", userInput);
}
为了简单起见,我没有包含其余代码。
比如我的输入是
xxx
输出是
Do you want to continue (yes/no) :
这很好。但是,如果我输入:
xxxx
输出是:
Do you want to continue (yes/no) :Do you want to continue (yes/no) :
如果我输入
xxxxxxx
我明白了
Do you want to continue (yes/no) :Do you want to continue (yes/no) :Do you want to continue (yes/no) :
看起来它几乎是在预期长度之后保存其余字符,并立即将它们发送到输入或其他什么?我想针对太长的字符串构建保护机制,但我认为这并不理想。
如果问题结构不当,我很抱歉,欢迎任何建设性的批评。我在任何地方都找不到这个确切的问题,所以我想问问自己。
最佳答案
当您使用 scanf("%3s", userInput)
时,它只会读取以 '\0'
结尾的 3
个字符到userInput
缓冲区。但是,如果您键入超过 3
个字符,其余字符仍存在于输入缓冲区中,等待 scanf
读取它。
您可以在每次 scanf
后清空缓冲区以避免这种意外。
#include <stdio.h>
#include <string.h>
int main(void)
{
char userInput[4];
userInput[0] = '\0';
int c;
while ((strcmp(userInput, "yes") != 0) && (strcmp(userInput, "no") != 0))
{
printf("Do you want to continue (yes/no) :");
scanf("%3s", userInput);
while(1) // drain the input
{
c = getchar ();
if(c=='\n') break;
if(c==EOF) return -1;
}
}
return 0;
}
关于c - 字符串比预期的要长,并被视为多个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49260938/