我想用 c 编写一个程序,在循环开始时要求用户输入,如果用户点击 Q 则结束 while 循环。 我正在寻找高效的代码并且没有 fflush() 调用。[我认为用户可以在输入中输入 'a'、'abc'、'ab2c' 等]。 我尝试了以下方式,但如果我按“a”,它还会包含“\0”,这会导致额外的循环调用。同样,如果用户输入 'abc' 或 'ab2c' 等,循环将执行多次。
int main (void)
{
char exit_char = '\0';
puts ("Entering main()");
while (1)
{
printf ("Please enter your choice: ");
exit_char = getchar();
if (exit_char == 'Q')
break;
f1();
}
return 0;
}
请提出合适的解决方案。
最佳答案
在像您这样的情况下,最好逐行读取输入,然后处理每一行。
#define MAX_LINE_LENGTH 200
char* getInput(char line[], size_t len)
{
printf ("Please enter your choice: ");
return fgets(line, len, stdin);
}
int main (void)
{
char line[MAX_LINE_LENGTH];
while ( getInput(line, sizeof(line)) )
{
if ( toupper(line[0]) == 'Q' )
break;
// Process the line
}
}
关于c - 输入 'Q' 时退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331905/