如何无需输入两次q即可终止C语言while循环?
输入两次q才能退出C语言程序的原因与解决方法
编写了一段C语言代码,用于输入物体名称及英寸长度并转换为英尺和英寸格式输出,但终止while循环时需要输入两次q才能退出,怀疑是输入缓冲区问题,但不清楚具体原因。
原代码
#include <stdio.h> #include <string.h> int main(void) { int Length, fLength, iLength; char sObject [25]; printf("Enter object and object length in inches (q to quit);\n"); while (scanf("%24s %d", sObject, &Length) > 1) { fLength = Length / 12; iLength = Length % 12; printf("The length of %s is %d foot %d inches\n", sObject, fLength, iLength); printf("Enter object and object length in inches (q to quit);\n"); } return 0; }
运行示例
Enter object and object length in inches (q to quit); bat 100 The length of bat is 8 foot 4 inches Enter object and object length in inches (q to quit); q q
问题原因
当输入q并回车时,scanf("%24s %d", ...)会先把q读取到sObject中,但后续的%d会跳过空白字符(包括换行)并等待有效数字输入,导致程序卡住,必须再次输入内容(比如q)。此时scanf再次读取sObject为q,%d依然匹配失败,返回值为1,不满足循环条件>1,程序才会退出。
解决方案
方案1:提前检查退出指令
先读取物体名称,判断是否为q,是则直接退出;否则读取长度并处理输入:
#include <stdio.h> #include <string.h> int main(void) { int Length, fLength, iLength; char sObject [25]; printf("Enter object and object length in inches (q to quit);\n"); while (scanf("%24s", sObject) == 1) { // 检测退出指令 if (strcmp(sObject, "q") == 0) { break; } // 读取长度,处理输入错误 if (scanf("%d", &Length) != 1) { // 清空输入缓冲区的残留内容 while (getchar() != '\n'); printf("无效输入,请重新输入物体名称和长度。\n"); printf("Enter object and object length in inches (q to quit);\n"); continue; } // 转换并输出结果 fLength = Length / 12; iLength = Length % 12; printf("The length of %s is %d foot %d inches\n", sObject, fLength, iLength); printf("Enter object and object length in inches (q to quit);\n"); } return 0; }
方案2:处理scanf返回值并清空缓冲区
通过判断scanf的返回值,处理不同输入情况,输入失败时清空缓冲区:
#include <stdio.h> #include <string.h> int main(void) { int Length, fLength, iLength; char sObject [25]; printf("Enter object and object length in inches (q to quit);\n"); while (1) { int ret = scanf("%24s %d", sObject, &Length); if (ret == 2) { // 成功读取两个输入,处理转换 fLength = Length / 12; iLength = Length % 12; printf("The length of %s is %d foot %d inches\n", sObject, fLength, iLength); printf("Enter object and object length in inches (q to quit);\n"); } else if (ret == 1) { // 只读取了字符串,检查是否为退出指令 if (strcmp(sObject, "q") == 0) { break; } // 清空缓冲区,提示重新输入 while (getchar() != '\n'); printf("无效输入,请输入物体名称和数字长度。\n"); printf("Enter object and object length in inches (q to quit);\n"); } else { // 读取失败(如EOF),直接退出 break; } } return 0; }
核心说明
两种方案的核心都是避免scanf的%d在输入无效时无限等待输入,通过提前检测退出指令或清空输入缓冲区,确保程序能及时响应退出操作。
内容的提问来源于stack exchange,提问作者Leopold149
相关产品推荐
相关产品推荐

