C语言程序输入问题:如何让程序等待分步输入(使用fgets)
问题解决办法
你的问题出在两个地方:一是scanf读整数后没清理缓冲区里的换行符,导致fgets直接读了空行;二是不知道怎么用scanf读取带空格的字符串。下面给你具体解决方法:
一、解决fgets不等待输入的问题
scanf("%d", &choice)读取完数字后,你按下的回车键会变成换行符留在输入缓冲区里。接下来调用fgets时,它会直接把这个换行符读进去,所以看起来没等你输入就执行完了。
解决方法是在scanf之后,手动清空缓冲区里的残留字符:
- 用
while(getchar() != '\n');把缓冲区里所有字符直到换行符全部清空,这是最稳妥的方式,能处理用户输入数字后附带其他字符的情况。
二、用scanf读取带空格的字符串
如果想用scanf读取包含空格的字符串,可以用%[^\n]格式符,它表示读取所有字符直到遇到换行符为止。必须限制读取长度,避免缓冲区溢出——比如你的数组是50位,就写%49[^\n](留一位存字符串结束符\0)。
同样,用这个格式符之前也要清理缓冲区的换行符,不然会直接读空。
修改后的代码示例
方案1:修复fgets的输入问题
#include<stdio.h> void input(char a[]){ printf("%s",a); } int main(){ char c[50]; int choice=1; while(choice!=0){ printf("\nEnter the number corresponding your choice\n1.Input 2. Output 3.Arithmetic"); scanf("%d",&choice); // 清空缓冲区残留的换行符 while(getchar() != '\n'); switch(choice){ case 1: printf("write input statement of C:\n"); fgets(c, sizeof(c), stdin); // 用sizeof自动获取数组长度,避免硬编码 input(c); break; case 2: break; case 3: break; case 4: break; case 5: break; default: printf("invalid choice enter again \n"); } } }
方案2:用scanf读取带空格的字符串
#include<stdio.h> void input(char a[]){ printf("%s",a); } int main(){ char c[50]; int choice=1; while(choice!=0){ printf("\nEnter the number corresponding your choice\n1.Input 2. Output 3.Arithmetic"); scanf("%d",&choice); // 清空缓冲区残留的换行符 while(getchar() != '\n'); switch(choice){ case 1: printf("write input statement of C:\n"); // 读取最多49个字符,直到换行符 scanf("%49[^\n]", c); printf("\n你输入的内容是:"); input(c); break; case 2: break; case 3: break; case 4: break; case 5: break; default: printf("invalid choice enter again \n"); } } }
注意:用%[^\n]时,如果用户直接按回车,会导致scanf失败,缓冲区里的换行符还会残留。如果要处理这种情况,可以检查scanf的返回值,或者提前处理空输入的场景。
内容的提问来源于stack exchange,提问作者ShobhitMaste
相关产品推荐
相关产品推荐

