使用scanf()读取多行输入

use*_*604 6 c scanf

相关代码段:

char input [1024];

printf("Enter text. Press enter on blank line to exit.\n");
scanf("%[^\n]", input);
Run Code Online (Sandbox Code Playgroud)

这将读取整个行,直到用户点击[enter],阻止用户进入第二行(如果他们愿意).

要退出,它们会再次按[enter]然后再按[enter].所以我尝试了各种while循环,for循环,以及涉及新行转义序列的scanf()周围的if语句,但似乎没有任何工作.

有任何想法吗?

tmy*_*ebu 5

尝试这个:

while (1 == scanf("%[^\n]%*c", input)) { /* process input */ }
Run Code Online (Sandbox Code Playgroud)

  • 为了确保安全,请将输入缓冲区的大小减 1 添加到格式说明符中。 (2认同)