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

时间:2014-08-18 23:46:12

标签: c string scanf

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

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

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

#include <stdio.h>

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

如果我输入&#34;只是一个测试&#34;当提示出现这种情况时,会发生以下情况:

Situation?
just a test
Action Taken?
Situation: just a test
Action: ��_��?�J.N=��J�J�d�����J0d���8d��TJ�J

任何建议或解决方案(fgets除外)?解释发生了什么也会很棒。

编辑:scanf: "%[^\n]" skips the 2nd input but " %[^\n]" does not. why?

处的解决方案

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

4 个答案:

答案 0 :(得分:2)

变化

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

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

答案 1 :(得分:2)

方法数量:

而不是以下不消耗 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);
    
  4. 无论采用何种解决方案,都要限制读取的最大字符数并检查函数的返回值。

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

解决方案一:使用scanf

如果您仍想通过scanf阅读,@ chux和@BLUEPLXY提供的答案已经足够了。像:

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

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

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

Because using gets() and 'fgets()` are unreliable sometimes.