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

问题描述 投票:0回答:4

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

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

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

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");
c string scanf
4个回答
2
投票

更改

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

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

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

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

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

1
投票

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


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.

© www.soinside.com 2019 - 2024. All rights reserved.