sscanf 无法从标准输入工作 space
sscanf not working space from stdin
我对 C 中的 sscanf 函数有一些问题。
我的程序
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[50];
int y=0, x=0;
printf("Insert string: ");
scanf("%s", str);
sscanf(str, "%d %d", &x, &y);
printf("x:%d y:%d\n",x,y);
return 0;
}
输入
10 20
输出
x:10 y:0
我也试过了
sscanf(str, "%d%d", &x, &y);
和
sscanf(str, "%d%*[ \n\t]%d", &x, &y);
但输出是一样的。
奇怪的是当我尝试
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[] = "10 20";
int y=0, x=0;
sscanf(str, "%d %d", &x, &y);
printf("x:%d y:%d\n",x,y);
return 0;
}
我的输出是x:10 y:20
那不是因为 sscanf
错误,而是 scanf
忽略了空格。
正如多次指出的那样 (How do you allow spaces to be entered using scanf?),您应该使用 fgets
来获取字符串输入。
所以用下面的行替换 scanf("%s", str);
就可以了:
fgets( str, 50, stdin );
我对 C 中的 sscanf 函数有一些问题。
我的程序
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[50];
int y=0, x=0;
printf("Insert string: ");
scanf("%s", str);
sscanf(str, "%d %d", &x, &y);
printf("x:%d y:%d\n",x,y);
return 0;
}
输入
10 20
输出
x:10 y:0
我也试过了
sscanf(str, "%d%d", &x, &y);
和
sscanf(str, "%d%*[ \n\t]%d", &x, &y);
但输出是一样的。
奇怪的是当我尝试
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[] = "10 20";
int y=0, x=0;
sscanf(str, "%d %d", &x, &y);
printf("x:%d y:%d\n",x,y);
return 0;
}
我的输出是x:10 y:20
那不是因为 sscanf
错误,而是 scanf
忽略了空格。
正如多次指出的那样 (How do you allow spaces to be entered using scanf?),您应该使用 fgets
来获取字符串输入。
所以用下面的行替换 scanf("%s", str);
就可以了:
fgets( str, 50, stdin );