在C中使用多个scanf时,使用scanf忽略空格的问题

我试图在一个小程序中多次使用scanf来获取保证有空格的输入。 从我浏览的多个线程看起来像scanf("%[^\n]", string); 是让它忽略空间的方法。 这适用于一行,但该行之后的任何其他scanf都没有通过,它们各自的字符串显示如下:

 Action: J   J Resolution: J:F J B J 

这是一些我认为可行的示例代码,但没有。

 #include  int main(void) { char str1[100]; char str2[100]; printf("Situation?\n"); scanf("%[^\n]", str1); printf("Action Taken?\n"); scanf("%[^\n]", str2); printf("Situation: %s\n",str1); printf("Action: %s\n",str2); } 

如果在提示输入情况时输入“Just a test”,则会发生以下情况:

 Situation? just a test Action Taken? Situation: just a test Action:   _  ? JN=  J J d     J0d   8d  TJ J 

任何建议或解决方案(不包括fgets )? 对正在发生的事情的解释也会很棒。

编辑: scanf上的解决方案:“%[^ \ n]”跳过第二个输入,但“%[^ \ n]”没有。 为什么?

添加char* fmt = "%[^\n]%*c"; 100%工作。

 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"); 

更改

 scanf("%[^\n]", str1); 

 scanf("%[^\n]%*c", str1);//consume a newline at the end of the line 

方法数量:

而不是以下不消耗Enter'\n' (这是问题):

 scanf("%[^\n]",str1); 
  1. 使用尾随换行符。 "%*1[\n]"只会消耗1 '\n' ,但不会保存它。

     scanf("%99[^\n]%*1[\n]" ,str1); 
  2. 在下一个scanf()上使用尾随换行符。 " "消耗前一个和前导的空白区域。

     scanf(" %99[^\n]", str1); 
  3. 使用fgets() ,但当然,这不是scanf() 。 最好的方法。

     fgets(str1, sizeof str1, stdin); 

无论采用何种解决方案,都要限制读取的最大字符数并检查函数的返回值。

  if (fgets(str1, sizeof str1, stdin) == NULL) Handle_EOForIOError(); 

我没有立即回答您的问题,如果您想要一行输入,为什么不简单地使用fgets (甚至获取 )?

解决方案一:使用scanf

如果您仍想通过scanf读取它,@ chux和@BLUEPLXY提供的答案就足够了。 喜欢:

  scanf(" %[^\n]", str); //notice a space is in the formatted string 

要么

  scanf("%[^\n]%*c", str); 

解决方案二:使用getline() (虽然它是POSIX扩展)

因为使用gets()和’fgets()`有时是不可靠的。