[英]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[\\n]"
仅消耗1 '\\n'
,但不保存。
scanf("%99[^\\n]%*1[\\n]" ,str1);
在下一个scanf()
上使用结尾的换行符。 " "
会占用先前的空白和前导空白。
scanf(" %99[^\\n]", str1);
使用fgets()
,但是当然不是scanf()
。 最好的方法。
fgets(str1, sizeof str1, stdin);
无论采用哪种解决方案,都应限制读取的最大字符数并检查函数的返回值。
if (fgets(str1, sizeof str1, stdin) == NULL) Handle_EOForIOError();
解决方案一:使用scanf
如果您仍然想用scanf
读取它,@chux和@BLUEPLXY提供的答案就足够了。 喜欢:
scanf(" %[^\n]", str); //notice a space is in the formatted string
要么
scanf("%[^\n]%*c", str);
解决方案二:使用getline()
(尽管它是POSIX扩展名)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.