如何正确使用fgets()避免bug并让句号与输出内容同行?
关于fgets()的两个常见问题解决方法
问题1:fgets读取后输出换行导致句号错位
原因:fgets()会将用户输入时按下的Enter键(即\n换行符)一并读取到缓冲区中,输出时%s会解析这个换行符,导致句号被挤到下一行。
解决方法:读取完成后手动移除换行符,以下是两种实现方式:
方式1:用strcspn()快速替换换行符
#include <stdio.h> #include <string.h> // 需引入string.h头文件 int main() { char motherName[30]; printf("Enter your mother's full name: "); fgets(motherName, sizeof(motherName), stdin); // 定位第一个换行符的位置,替换为字符串结束符'\0' motherName[strcspn(motherName, "\n")] = '\0'; printf("Your mom's full name is %s.", motherName); return 0; }
方式2:手动遍历字符串替换
#include <stdio.h> #include <string.h> int main() { char motherName[30]; printf("Enter your mother's full name: "); fgets(motherName, sizeof(motherName), stdin); size_t len = strlen(motherName); // 判断最后一个字符是否为换行符,是则替换为结束符 if (len > 0 && motherName[len-1] == '\n') { motherName[len-1] = '\0'; } printf("Your mom's full name is %s.", motherName); return 0; }
问题2:fgets与scanf混用时无法获取输入
原因:scanf("%d")和scanf("%s")仅读取目标内容,不会处理输入缓冲区中残留的\n换行符。当执行到fgets()时,它会直接读取缓冲区里的空换行,导致看起来没有获取到输入。
解决方法:在调用fgets()前清空输入缓冲区的残留字符,以下是三种可行方案:
方案1:用getchar()循环清空缓冲区
#include <stdio.h> int main() { int num; printf("What's your favorite number: "); scanf("%d", &num); printf("Your favorite number is %d.\n", num); // 循环读取直到清空换行符 while (getchar() != '\n'); char name[20]; printf("Enter your name: "); scanf("%s", name); printf("Your name is %s.\n", name); // 再次清空缓冲区换行符 while (getchar() != '\n'); char motherName[30]; printf("Enter your mother's full name: "); fgets(motherName, sizeof(motherName), stdin); // 移除fgets读取的换行符 motherName[strcspn(motherName, "\n")] = '\0'; printf("%s is your mom's full name.", motherName); return 0; }
方案2:用scanf格式符跳过残留字符
在每个scanf执行后,用以下代码清空缓冲区:
scanf("%d", &num); printf("Your favorite number is %d.\n", num); // 跳过所有非换行字符,再跳过换行符 scanf("%*[^\n]"); scanf("%*c");
注:即使用户输入后直接按回车,scanf("%*c")依然会读取换行符,不影响效果。
方案3:统一用fgets处理所有输入
避免混用输入函数,全部用fgets()读取,再用sscanf()解析数字或单字段内容:
#include <stdio.h> #include <string.h> int main() { char input[50]; int num; printf("What's your favorite number: "); fgets(input, sizeof(input), stdin); sscanf(input, "%d", &num); printf("Your favorite number is %d.\n", num); char name[20]; printf("Enter your name: "); fgets(input, sizeof(input), stdin); sscanf(input, "%s", name); printf("Your name is %s.\n", name); char motherName[30]; printf("Enter your mother's full name: "); fgets(motherName, sizeof(motherName), stdin); motherName[strcspn(motherName, "\n")] = '\0'; printf("%s is your mom's full name.", motherName); return 0; }
内容的提问来源于stack exchange,提问作者Greeshma
相关产品推荐
相关产品推荐

