C语言读取客户信息输出时自动换行的问题如何解决
问题根因
- 你当前代码用到的
fgets()函数默认会将用户输入结束时按下的换行符\n一同存入目标字符串的末尾,所以三个读取到的字段尾部都自带换行符,输出时就会自动分行。 - 你的输入逻辑存在冗余:对同一个存储变量你先后调用了
scanf_s()和fgets(),重复读取还可能读取到输入缓冲区的残留换行,进一步加重异常。
修复方案
- 简化输入逻辑,仅使用
fgets()读取整行输入即可 - 每次读取完字段后,主动清除字符串末尾的换行符,这里推荐用
strcspn()函数实现,无需额外判断字段末尾是否存在换行,兼容性更好
修正后可运行代码
#include <stdio.h> #include <string.h> // 引入头文件使用strcspn #define VARSIZE 80 int main(void) { char customerName[VARSIZE], ID[VARSIZE], phoneNumber[VARSIZE]; puts("Input the following:"); puts("First and last name"); printf(">"); fgets(customerName, VARSIZE, stdin); // 去除末尾换行符 customerName[strcspn(customerName, "\n")] = '\0'; printf("Enter ID for %s", customerName); printf(">"); fgets(ID, VARSIZE, stdin); ID[strcspn(ID, "\n")] = '\0'; printf("Enter phone number for %s", customerName); printf(">"); fgets(phoneNumber, VARSIZE, stdin); phoneNumber[strcspn(phoneNumber, "\n")] = '\0'; puts("\nUser registered!\nYou will be placed back in the menu now.\n"); // 写入文件的逻辑,空格分隔三个字段,末尾加换行方便后续逐行读取 //fprintf(write_file, "%s %s %s\n", customerName, ID, phoneNumber); printf("%s %s %s", customerName, ID, phoneNumber); return 0; }
说明
strcspn()会返回字符串从开头到第一次遇到目标字符的长度,直接给这个位置赋值为\0即可截断末尾的换行- 写入文件时按
%s %s %s\n格式输出,就能保证三个字段在同一行用空格分隔,后续读取时直接按行读取再按空格拆分即可完成解析
内容的提问来源于stack exchange,提问作者Mirax
相关产品推荐
相关产品推荐

