C 中 fgets() 的问题

Problems with fgets() in C

我正在尝试使用 fgets() 将两个字符存储在两个不同的字符中。

char tobereplaced[1], replacedwith[1];
printf("Please enter character to be replaced\n");
fflush(stdin);
fgets(tobereplaced, 2, stdin);
printf("Please enter character to replace with\n");
fflush(stdin);
fgets(replacedwith, 2, stdin);
printf("User asks to replace \'%s\' with \'%s\'\n", tobereplaced, replacedwith);

如果我输入 'a' 和 'b' 我得到以下输出:

User asks to replace '' with 'b'

所以我的问题是为什么只有第二个值被存储而第一个没有?

请注意,我使用“2”作为 fgets() 中的第二个参数,因为如果我使用“1”(对我来说这似乎是显而易见的值),它不会因为某种原因停止并等待输入。

函数fgets存储一个C字符串,以空字符结束,或者'[=11=]',你需要space来存储这个字符,否则它将出乎意料地工作。在您的情况下,只需将数组大小更改为 2 或使用 getchar().

之类的函数

fgets() 尝试读取 的输入(所有字符直至并包括 '\n')。然后它附加一个 空字符 .

With input aEnter, fgets() 想要至少一个 tobereplaced[3] array to store store the 'a''\n''[=18=]'

以下代码 不好 因为它错误地告诉 fgets()tobereplaced[]

中有 2 个 char 可用
char tobereplaced[1];           // Only 1
fgets(tobereplaced, 2, stdin);  // bad, UB, said it was 2

取而代之的是读取一行,并带有额外的 space 以防用户输入一些额外的字符:

char tobereplaced[80];
fgets(tobereplaced, sizeof tobereplaced, stdin);

printf("Please enter character to replace with\n");
char replacedwith[80];
fgets(tobereplaced, sizeof tobereplaced, stdin);

printf("User asks to replace \'%c\' with \'%c\'\n", tobereplaced[0], replacedwith[0]);

Regarding the fflush(stdin). If I remove then the fgets won't stop and wait for input. How can I solve this problem without using the fflush? Or am I missing something crucial here?

当然是因为使用了之前的 scanf(),在 stdin 中留下了 '\n'fgets() 不必停下来等待输入,因为 stdin 中还有剩余的 '\n' 需要读取。 fflush(stdin) 未定义的行为

我建议仅使用 fgets() 进行用户输入。
在你明白为什么它不好之前不要使用 scanf()