gpt4 book ai didi

c - 无法向代码添加正确的错误检查

转载 作者:行者123 更新时间:2023-11-30 14:37:48 25 4
gpt4 key购买 nike

对于我的作业,我得到了一个程序来添加错误检查,我快速添加了前两个(我相信我已经解决了后面带有 X 的任何注释)但是我相信此错误检查的问题是一致的60 是 fscanf 愿意将字符读入需要整数的内容,因此我需要添加一些内容,以便在尝试读入字符时打印出错误并停止程序。我也不是确定在 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;
}

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

最佳答案

如何进行错误检查:

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] 始终是可执行文件的名称

关于c - 无法向代码添加正确的错误检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57000611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com