C语言while循环中scanf字符读取的缓冲区异常问题排查求助
C语言算术运算程序输入多字符后自动触发错误的解决方法
问题描述
我编写了一段实现算术运算选择功能的C语言代码,运行时发现输入多个字符(如"00")后,后续while循环无需用户输入就自动触发"Unknown command"错误提示。已在scanf的%c前添加空格处理缓冲区,但问题仍存在。
原代码
void EX18() { float x, y; char op; int i = 0; while (1) { /* printf("\n******************** \n"); printf("A ---- Add \n"); printf("S ---- Subtract \n"); printf("M ---- Multiply \n"); printf("D ---- Divide \n"); printf("Q ---- Quit \n"); printf("******************** \n"); */ i++; printf("\n%dth iteration \n",i); printf("Select an operation: "); scanf(" %c", &op); if (op == 'Q') break; else { switch (op) { case 'A': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); printf("%.2f \n", x + y); break; case 'S': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); printf("%.2f \n", x - y); break; case 'M': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); printf("%.2f \n", x * y); break; case 'D': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); printf("%.2f \n", x / y); break; default: printf("\nUnknown command. Please try again.\n"); } } } } int main() { EX18(); //TEST5(); return 0; }
异常运行现象
第1次迭代
选择操作:00未知命令,请重试。
第2次迭代
选择操作:
未知命令,请重试。第3次迭代
选择操作:000未知命令,请重试。
第4次迭代
选择操作:
未知命令,请重试。第5次迭代
选择操作:
未知命令,请重试。
问题原因
scanf(" %c", &op)只会读取输入缓冲区中的第一个非空白字符,输入的多余字符(比如输入"00"时的第二个'0')会残留在缓冲区里。下一次循环执行时,scanf会直接读取这些残留字符,跳过用户输入步骤,直接触发default分支的错误提示。
解决方法
每次读取操作符后,清空输入缓冲区中剩余的所有字符,避免残留内容干扰后续输入。可以用getchar()循环读取直到换行符,丢弃所有残留字符。
修改后的完整代码
void EX18() { float x, y; char op; int i = 0; while (1) { i++; printf("\n%dth iteration \n",i); printf("Select an operation: "); scanf(" %c", &op); // 清空输入缓冲区的残留字符 while ((getchar()) != '\n'); if (op == 'Q') break; else { switch (op) { case 'A': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); // 读取数字后同样清空缓冲区,避免后续输入受干扰 while ((getchar()) != '\n'); printf("%.2f \n", x + y); break; case 'S': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); while ((getchar()) != '\n'); printf("%.2f \n", x - y); break; case 'M': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); while ((getchar()) != '\n'); printf("%.2f \n", x * y); break; case 'D': printf("Enter two numbers separated by a space: "); scanf("%f %f", &x, &y); while ((getchar()) != '\n'); printf("%.2f \n", x / y); break; default: printf("\nUnknown command. Please try again.\n"); } } } } int main() { EX18(); return 0; }
补充说明
- 读取操作符后的缓冲区清空是核心,确保下一次
scanf获取的是用户新输入的内容。 - 读取浮点数后也建议清空缓冲区,防止用户输入数字后附带的其他字符残留,影响后续循环的操作符读取。
内容的提问来源于stack exchange,提问作者Gongback Kim
相关产品推荐
相关产品推荐

