C 中不需要的换行符

Unwanted line break in C

我用 C 语言创建了一个小脚本,它在 Linux 控制台中显示文本,但我发现了一个问题 - 该脚本在文本末尾添加了一个换行符。我不知道为什么,通常我应该在 /n.

之后换行
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char buf[1024];
    char txt[100];
    printf("Insert a text: ");
    fgets(txt, 100, stdin);
    snprintf(buf, sizeof(buf), "echo '%s'", txt);
    system(buf);
}

代码结构必须保持不变。我需要使用系统函数和 snprintf().

我想说清楚几件事。当我 运行 这个脚本时,输出看起来像这样:

root@test:/home# ./app
Insert a text: Hello
Hello

root@test:/home#

如何在 Hello 之后删除这个换行符?

您面临的问题与 fgets() 的行为有关。根据 man page

char *fgets(char *s, int size, FILE *stream);

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

因此,它读取并存储在输入 txt 后按 ENTER 生成的尾随 \n(换行符)。如果您不希望 \n 出现在 txt 中,您需要在打印 txt.

的内容之前手动将其从输入缓冲区中删除

您可以使用 strchr()strcspn() 找出 可能 \n 并将其替换为 [=27=] (null) 来解决您的问题。

fgets 消耗输入数据后按下的缓冲区中的 \n 字符。只需添加

txt[strcspn(txt,"\n")] = 0;

紧跟在 fgets 之后,用 NUL 终止符替换 txt 末尾的 \n 字符。在您的例子中,strcspn function 计算 txt 中的字符数,直到 \n 字符。如果没有找到换行符,那么它 returns txt(strlen(txt)).

的长度

顺便说一句,如果你想使用这个功能,你需要包含string.h

#include <string.h>