繁体   English   中英

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

[英]Issues ignoring spaces with scanf when using multiple scanf's in C

我试图在一个小程序中多次使用scanf来获取保证有空格的输入。 尽管看起来像scanf("%[^\\n]", string);但是从多个线程中浏览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]”跳过第二个输入,但“%[^ \\ 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 (甚至是gets )呢?

解决方案一:使用scanf

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

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

要么

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM