我试图在一个小程序中多次使用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");
更改
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扩展)
Because using gets()
and 'fgets()` are unreliable sometimes.