当我输入多个字符时,如何将输出限制为仅一个响应。
#include <stdio.h>
main(){
char answer;
printf("Do you want to continue(Y/N)?");
scanf("%c", &answer);
while ((answer != 'Y') && (answer != 'N')){
printf("\nYou must type a Y or an N\n");
printf("Do you want to continue(Y/N) ?");
scanf(" %c", &answer);
}
return 0;
}
最佳答案
使用 getchar() 读取第一个字符,然后读取下一个字符,直到 EOF。
此外,循环外部(之前)的读取是不必要的。
#include <stdio.h>
// additional function for reading remaining input
void flush();
main(){
// answer needs to be int, because getchar() can return -1 in case of EOF
int answer;
while (1) {
printf("Do you want to continue(Y/N)? ");
answer = getchar();
// read and ignore the remaining input
flush();
if ((answer == 'Y') || (answer == 'N'))
break; // exit loop
printf("\nYou must type a Y or an N\n");
}
// here answer contains 'Y' or 'N'
// do what you need with this...
return 0;
}
// function for consuming the remaining input
void flush()
{
while (getchar() != EOF); // consume input until emptying
}
关于c - 如何减少多个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59431862/