c - Sscanf 问题和从命令行读取

标签 c command-line segmentation-fault scanf

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

a.out [23+10i]

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

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

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

最佳答案

对我有用

#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 指针。

关于c - Sscanf 问题和从命令行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4382769/

相关文章:

c++ - 递归调用段错误问题

c - 打印 size_t : format '%lu' expects argument of type 'long unsigned int'

c - 整数指针和 'incompatible pointer type warning'

java - Maven -> Update Project... 究竟是什么?

ruby-on-rails - 从Rails控制台删除多个记录

c++ - gsl_histogram_find 给出段错误(c++,gsl)

c中的字符比较段错误

c - 如何使用c程序检查子目录是否包含文本文件

c - 为什么unsigned char变量包含EOF?

从命令行使用 sql 身份验证的 sqlcmd