【发布时间】:2019-07-12 05:21:45
【问题描述】:
对于我的任务,我得到了一个添加错误检查的程序,我快速添加了前两个(我相信我已经解决了任何带有 X 的注释)但是我相信这个错误检查的问题60 是fscanf 愿意将字符读入需要整数的东西,所以我需要添加一些打印出错误并在尝试读入字符时停止程序的内容。我也不确定要检查什么错误在create_graph 和read_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;
}
现在程序只是在尝试读取文件时崩溃。
【问题讨论】:
-
您使用 both
fscanf和scanf从文件填充,丢弃,然后从控制台填充的原因,相同变量n和m是... ???应该检查的是fscanf。scanf甚至不应该在那里。 -
OT:此检查错误:
if (argv[2] != '\0')这不是检查argv[1]是否存在的方法。使用if (argc < 2) -
对于这个
fscanf(file, "%d %d", &n, &m);你需要做if (fscanf(file, "%d %d", &n, &m) != 2) { // add error handling code }; -
此代码
.vertices = calloc(n, sizeof(vertex)),缺少对 NULL 的检查 -
谨记@4386427 的评论:
read_edge()可能会失败,如果到达文件的任一端或文件有问题。我会考虑在这种情况下read_edge()应该返回什么以表示无法读取边缘。可能是包含无效值的edge。当然,这必须在调用read_edge()之后以及在对返回的edge值执行任何其他操作之前进行检查。
标签: c visual-studio-code error-checking