c - 如何从动态字符串中删除换行符
问题描述
我有这段代码可以输入各种字符串。他们最后不必有换行符,我需要它们一个接一个,因为我将它们写在一个 CSV 文件上。我放了一会儿
do {
printf("Put the ingredient:\n");
fgets(recipe.ingredients[j], 30, stdin);
len = strlen(recipe.ingredients[j]) + 1;
recipe.ingredients[len] == "\0";
fprintf(fbr, "%s,", recipe.ingredients[j]);
j++;
counter++;
printf("Do you want to continue? (yes/no)");
fgets(sentinel, 4, stdin);
} while(strcmp("yes", sentinel) == 0);
问题是,我输入的第一个字符串没有换行符,因为我设置了那个条件。我尝试增加和减少1
长度,但在这两种情况下,我只有第一个字符串没有换行符,而其他字符串无论如何都有换行符。我认为通过用空终止符替换换行符可以解决我的问题,但也许我遗漏了一些东西。有什么提示可以解决这个问题吗?我有点困惑……
解决方案
贴出的代码片段有很多问题:
- 您不测试 的返回值,如果失败,
fgets()
则在访问缓冲区内容时会导致未定义的行为。fgets()
- 该调用
fgets(sentinel,4,stdin);
最多只能读取 3 个字节sentinel
,以便为结尾的空终止符保留空间。因此,用户在之后输入的换行符yes
将保留在输入流中,并导致下一次调用fgets()
立即返回,缓冲区内容为"\n"
. len = strlen(recipe.ingredients[j]) + 1;
太大:换行符的偏移量将是strlen(recipe.ingredients[j]) - 1
如果它存在并且如果recipe.ingredients[j]
不是空字符串。recipe.ingredients[len] == "\0";
完全是假的:它只是一个比较,而不是一个作业,它比较了苹果和橘子: achar
和 aconst char *
。
如果存在则去除换行符的一种更简单的方法是:
char *p = recipe.ingredients[j];
p[strcspn(p, "\n")] = '\0'; // overwrite the newline, if present
这是修改后的版本:
for (;;) {
char sentinel[100];
char *p;
printf("Put the ingredient: ");
if (!fgets(recipe.ingredients[j], 30, stdin))
break;
p = recipe.ingredients[j];
p[strcspn(p, "\n")] = '\0'; // overwrite the newline, if present
fprintf(fbr, "%s,", recipe.ingredients[j]);
j++;
counter++;
printf("Do you want to continue? (yes/no): ");
if (!fgets(sentinel, sizeof sentinel, stdin))
break;
if (strcmp(sentinel, "yes") != 0)
break;
}
请注意,您还应该检查j
不会增加超出数组的大小recipe.ingredient
。
推荐阅读
- javascript - 更改 Outlook 的电子邮件主题
- powerbi - 使用 IF 或 ALLEXCEPT 求和
- html - 创建 html 链接以下载和安装配置文件
- android - Android Oreo 上的广播接收器
- javascript - 找不到图像/无法获取 /uploads/image nodejs REST API
- linux - 安装审计时出错
- c# - Payfast 通知 url 测试 c#
- javascript - 有什么方法可以读取 openlayers 4 中的 geojson 属性吗?
- java - 从游戏返回菜单
- arduino - 如果 rx 和 tx 线断开连接,如何制作一个执行某些操作的程序?