如何用scanf读取空格
问题描述:
尽管我在scanf("[^\n]s", x)
或"%34[^\n]"
或%127s
中使用此条件,但我无法正确得到答案。是否存在与scanf
区域或其他部分的任何问题....如何用scanf读取空格
#include <stdio.h>
int main()
{
int i = 4;
double d = 4.0;
char s[] = "hello ";
int a;
double b;
unsigned char string_2[100];
scanf("%d",&a);
scanf("%lf",&b);
scanf("%[^\n]s",string_2);
printf("%d",a+i);
printf("\n%lf",d+b);
printf("\n%s",s);
printf("%s",string_2);
return(0);
}
答
不要使用scanf
这样。
在此:
scanf("%lf",&b);
scanf("%[^\n]s",string_2);
第一scanf
读取输入一个数字,而是需要等待终端先给程序输入的完整产品线。假设用户123
,所以程序从操作系统读取123\n
。
scanf
看到不再是该数字的一部分的换行符,并停在离开换行符在输入缓冲区(在stdio中)。第二个scanf
试图读取非新行的东西,但不能这样做,因为它看到的第一件事是换行符。如果您检查scanf
调用的返回值,则会看到第二个scanf返回零,即无法完成您要求的转换。
相反,读满线的时间,与fgets
或getline
:
#include <stdio.h>
int main(void)
{
char *buf = NULL;
size_t n = 0;
double f;
getline(&buf, &n, stdin);
if (sscanf(buf, "%lf", &f) == 1) {
printf("you gave the number %lf\n", f);
}
getline(&buf, &n, stdin);
printf("you entered the string: %s\n", buf);
return 0;
}
对于较长的讨论,请参见:http://c-faq.com/stdio/scanfprobs.html
'的scanf( “%LF”,&b); 的scanf(“% [^ \ n] s“,string_2);' - >'scanf(”%lf“,&b); while(getchar()!='\ n'); scanf(”%99 [^ \ n]“, string_2);' – BLUEPIXY
是的,没有工作的人... awsome ....... – Nivethithan