2016-11-05 50 views
0

的工作空间,我有一些问题与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; 
} 

输入sscanf函数

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

+2

如果你的输出'str'了'后的scanf( “%s” 时,STR);',你会发现poblem。 – WhatsUp

+1

'%s'停止在第一个空格字符处读取输入。 –

回答

1

这并不是因为sscanf故障,那就是scanf忽略空白。

正如多次指出(How do you allow spaces to be entered using scanf?),您应该使用fgets来代替字符串输入。

因此与线替换scanf("%s", str);下面将工作:

fgets(str, 50, stdin);