Riz920 Riz920 - 28 days ago 16
C Question

sscanf not working space from stdin

I have some issue with sscanf function in C.

My program

#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;
}


Input

10 20


Output

x:10 y:0


I also tried

sscanf(str, "%d%d", &x, &y);


and

sscanf(str, "%d%*[ \n\t]%d", &x, &y);


but the output is the same.

The strange thing is that when I try

#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;
}


my output is
x:10 y:20

Answer

That's not because sscanf fault, it's that scanf ignore whitespace.

As pointed out many times (How do you allow spaces to be entered using scanf?), you should use fgets instead to get string input.

So replacing scanf("%s", str); with the line below would work:

fgets( str, 50, stdin );
Comments