无法在代码中添加正确的错误检查

时间:2019-07-12 05:21:45

标签: c visual-studio-code error-checking

对于我的任务,我得到了一个程序来添加错误检查,我快速添加了前两个(我认为已经解决了之后再加上X的任何注释),但是我相信此错误检查的问题所在60的原因是fscanf愿意将char读入带整数的对象中,因此,如果尝试读取char,我需要添加一些打印出错误并停止程序的内容。我也不知道该怎么做。在create_graphread_edge中进行错误检查。要读入该程序的文件的格式如下:

4 5
1 2 0.2
2 3 0.3
3 4 -3.7
1 4 0.2
3 1 0.4

我最近的尝试是:

   if (scanf("%d", &n) == 0 || scanf("%d", &m) == 0){
    printf("Error: Expected an Integer");

    return 0;
}

当前代码:

to try and scan the input to make sure they're integers.

// missing error check (you may need to modify the function's return
// value and/or parameters)
edge read_edge(FILE* file) {
    edge e;
    fscanf(file, "%d %d %f", &e.source, &e.target, &e.weight);
    return e;
}

graph create_graph(int n, int m) {
    graph g = {
        .n = n,
        .m = m,
        .vertices = calloc(n, sizeof(vertex)),
        .edges = calloc(m, sizeof(edge)),
    };

    for(int i = 0; i < n; i++) {
        g.vertices[i] = i + 1;
    }

    return g;
}

int main(int argc, char* argv[]) {
    // missing error check -- related to argc/argv X
    if (argv[2] != '\0')
    {
        printf("Wrong number of arguments.\n");
        return 0;
    }
    // missing error check (errno) X
    FILE* file = fopen(argv[1], "r");

    if (file == NULL) {
        printf("Unable to open file: %s\n", strerror(errno));
        return 0;
    }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    int n, m;
    // missing error check
    fscanf(file, "%d %d", &n, &m);

    if (scanf("%d", &n) == 0 || scanf("%d", &m) == 0){
        printf("Error: Expected an Integer");

        return 0;
    }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
    graph g = create_graph(n, m);

    for (int i = 0; i < m; i++) {
        // missing error check (after you fix read_edge)
        g.edges[i] = read_edge(file);
    }

    printf("%d %d\n", g.n, g.m);

    return 0;
}

现在,程序只是在尝试读取文件时崩溃。

1 个答案:

答案 0 :(得分:0)

如何进行错误检查:

fscanf(file, "%d %d", &n, &m);

建议:

if( fscanf(file, "%d %d", &n, &m) != 2 )
{
    fprintf( "fscanf of first line from the input file failed\n );
    exit( EXIT_FAILURE );
}

// implied else, fscanf successful

注意:scanf()函数家族返回成功的输入格式转换(或EOF)的次数

关于:

if (argv[2] != '\0')
{
    printf("Wrong number of arguments.\n");
    return 0;
}

在讨论命令行参数问题时,最好在stderr上显示USAGE语句,类似于:

if( argc != 2 )
{
    fprintf( stderr, "USAGE: %s <inputFileName>\n", argv[0] );
    exit( EXIT_FAILURE );
}

// implied else, correct number of command line parameters

注意:argv[0]始终是可执行文件的名称