fgets() 函数在打印字符串时自动换行

fgets() function atomatically breaking line when string is printed

#include <stdio.h>

void main () {
    char str[5];
    fgets(str, sizeof(str), stdin);
    printf("%s.", str);
}

我用 C 编写了这个简单的代码,我试图在一行中打印一个字符串和一个点,但是每当我输入一个包含 3 个或更少字符的字符串时,输出在细绳。

输入:

abc

输出:

abc
.

如果我输入的内容刚好是 4 个字符,输出结果就是我想要的,没有换行符。

我试过使用 gets() 和 scanf() 函数,它们运行良好,但我无法使用它们。

有人知道为什么会这样吗?

这个问题的解释在documentation of fgets:

Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

这正是您的情况:str 包含输入字符串 "abc",后跟 '\n',它在 "abc" 和点 [=16] 之间打印=].

问题是 fgets() 读取换行符 char。您需要取出附加在 char 数组中的换行符。

之后 fgets(str, sizeof(str), stdin); 你可以写在下面一行来去掉那个换行符

str[strlen(str)-1]='[=15=]'; 或者你也可以这样做,

char * p=NULL;
p= strchr(str,'\n');
if(p!=NULL)
{
 *p='[=10=]';
}