2016-11-05 56 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);