使用do while循环结合scanf打印字符串时遇多字符串自动输出问题求助
问题分析与解决
问题原因
scanf("%s") 以空白字符(空格、换行、制表符等)作为分隔符,仅读取第一个空白前的内容。当输入Name1 Name2 Name3并回车后,输入缓冲区留存Name1 Name2 Name3\n:
- 第一次循环:
scanf("%s")读取Name1,缓冲区剩余Name2 Name3\n;随后scanf("%d", &i)遇到非数字的Name2,读取失败,i保持之前的有效值(比如1),循环继续。 - 第二次循环:
scanf("%s")直接从缓冲区读取Name2,剩余Name3\n;scanf("%d")再次读取失败,循环继续。 - 第三次循环:
scanf("%s")读取Name3,剩余\n;scanf("%d")仍无法读取有效数字,直到手动输入0才终止程序。
解决方案
方案1:读取含空格的整行字符串
用fgets替代scanf("%s"),可以读取包含空格的整行输入,同时处理换行符残留:
#include <stdio.h> #include <string.h> int main() { int i; do { char str[20]; printf("\nEnter the String: "); fgets(str, sizeof(str), stdin); // 移除fgets读取的换行符 str[strcspn(str, "\n")] = '\0'; printf("The String is %s", str); printf("\n\nEnter the Number 1 to restart and 0 to terminate: "); // 清空缓冲区残留内容 while ((getchar()) != '\n'); scanf("%d", &i); // 清空数字输入后的换行符 while ((getchar()) != '\n'); } while (i != 0); return 0; }
方案2:保留scanf并清空缓冲区
如果坚持使用scanf("%s"),每次输入后清空缓冲区残留的空白与字符,避免影响后续读取:
#include <stdio.h> int main() { int i; do { char str[20]; printf("\nEnter the String: "); scanf("%s", str); printf("The String is %s", str); // 清空字符串输入后的缓冲区残留 while ((getchar()) != '\n'); printf("\n\nEnter the Number 1 to restart and 0 to terminate: "); scanf("%d", &i); // 清空数字输入后的换行符 while ((getchar()) != '\n'); } while (i != 0); return 0; }
补充说明
fgets是处理带空格字符串的更可靠方式,但会读取输入末尾的换行符,需手动移除。while ((getchar()) != '\n')循环会逐个读取缓冲区字符直到换行,彻底清空残留内容,避免后续读取异常。
内容的提问来源于stack exchange,提问作者Venkat V
相关产品推荐
相关产品推荐

