C 在终端执行C文件时,如何在fgets()或scanf()提示时在输入中添加换行符?

C When executing C file in terminal, how can I add line break to input when prompted by fgets() or scanf()?

场景一

char string[MAX_BYTES] = "This is a string\nthat I'm using\nfor scenario 1";

场景二

printf("Enter string: ");
fgets(string, MAX_BYTES, stdin);

如果我在代码中提供字符串(场景 1),我可以用 '\n'.

换行

但是如果在终端中使用 fgets()scanf() 进行提示(场景 2),则按 enter 会继续执行代码。

如何在不触发其余代码的情况下向输入添加换行符?

通常无法使用 fgetsscanf 来完成,但您可以使用 getchar 代替:

int ch;
int idx = 0;
while( ( (ch = getchar()) != EOF ) && idx < MAX_BYTES)
{
    string[idx++] = ch;
}
printf("%s", string);

注意 getchar 将接受任何输入,包括 \n 并且 while 循环在 EOF 时终止,即 Ctrl+D来自 stdin。然后将每个字符相应地复制到缓冲区。