2010-12-07 75 views
0

你好哈哈又一次。 C-的Unix 林讀取這樣的事情:Sscanf問題和從命令行讀取

a.out的[23 + 10I]

sscanf(argv[count], "[%d%c%di]", &a, &operand1, &b); 

欲分離如下: 一個= 23 B = 10 操作數='+ ' 但即時獲得segfault(核心轉儲)錯誤,我做錯了什麼?

順便說一句,非常感謝回答我的所有愚蠢的問題

+0

`count`的值是多少? `a`,`operand1`和`b`的聲明是什麼? – 2010-12-07 23:35:21

回答

4

它爲我

#include <stdio.h> 
int main(int argc, char **argv) { 
    int a, b; 
    char operand1; 
    int n; 

    printf("scanning argv[argc - 1]: %s\n", argv[argc - 1]); 
    /* It works for me */ 
    n = sscanf(argv[argc - 1], "[%d%c%di]", &a, &operand1, &b); 

    printf("%d values read\n", n); 
    if (n != 3) printf("there was an error in scanf ...\n"); 
    printf("The values were %d, %c, and %d\n", a, operand1, b); 
    return 0; 
} 

和樣品運行:

 
$ ./a.out [23+43i] 
scanning argv[argc - 1]: [23+43i] 
3 values read 
The values were 23, +, and 43 

注意argv[argc]是NULL指針。