考虑以下代码:
#include <stdio.h>
int main (void)
{
char str1[128], str2[128], str3[128];
printf ("\nEnter str1: ");
scanf ("%[^\n]", str1);
printf ("\nstr1 = %s", str1);
printf ("\nEnter str2: ");
scanf ("%[^\n]", str2);
printf ("\nstr2 = %s", str2);
printf ("\nEnter str3: ");
scanf ("%[^\n]", str3);
printf ("\nstr3 = %s", str3);
printf ("\n");
return 0;
}
当只执行第一个scanf
时停止等待提示。程序不会停止下一个 scanf
s。但如果格式字符串从 "%[^\n]"
更改为至" %[^\n]"
(注意 %
之前的空格),然后就可以了。是否自动接受先前输入缓冲区中的某些现有换行符?但脸红stdin
并没有解决这个问题。
这是什么原因造成的。
最佳答案
您只需在阅读完所需内容后“使用”'\n'
字符即可。使用以下格式指令:
"%[^\n]%*c"
它将把换行符之前的所有内容读入您传入的字符串中,然后将消耗单个字符(换行符)而不将其分配给任何内容('*'
是“分配抑制” )。
否则,换行符将留在输入流中,等待立即终止后续的 "%[^\n]"
格式指令。
向格式指令添加空格字符 ("%[^\n]"
) 的问题是该空格将匹配任何空白。因此,它将吃掉前一个输入末尾的换行符,但它也会吃掉任何其他空白(包括多个换行符)。
更新您的示例:
char* fmt = "%[^\n]%*c";
printf ("\nEnter str1: ");
scanf (fmt, str1);
printf ("\nstr1 = %s", str1);
printf ("\nEnter str2: ");
scanf (fmt, str2);
printf ("\nstr2 = %s", str2);
printf ("\nEnter str3: ");
scanf (fmt, str3);
printf ("\nstr2 = %s", str3);
printf ("\n");
关于c - scanf: "%[^\n]"跳过第二个输入,但 "%[^\n]"不会。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937996/