Sscanf问题和从命令行读取

时间:2010-12-07 23:31:49

标签: c command-line segmentation-fault scanf

你好哈哈哈。 C- Unix 我正在读这样的东西:

a.out [23 + 10i]

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

我想分开如下: 一个= 23 B = 10 操作数= '+' 但我得到了段错(核心转储)错误,我做错了什么?

顺便说一下,非常感谢回答我所有愚蠢的问题

1 个答案:

答案 0 :(得分: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]是空指针。