首页 > 解决方案 > 程序返回错误值

问题描述

我的 C 代码的以下部分有问题:

  // reading pairs of parameters from input file
  while((read = fscanf(input_file, "%d %d\n", &type, &col)) > 0 ) {
    // checking reading errors
    if (read != 2 || (type < 0 && type > 4) || (col > 9)) {
     printf("Invalid input file format\n");
      return 2;
    }
    // putting tetromino corresponding to given parameters to the field
    if (put_tetromino(field, type, col) != 0) {
      // if result is not 0, the tetromnio is out of range. Returning error
      printf("Tetromino is out of field\n");
      return 2;
    }
  }

输入文件如下所示:

5 0 
3 9
2 9
2 4 
..

在上面的代码部分中,我想检查输入文件是否具有正确的格式。我应该有 2 列:第一列(type)必须是 0 到 4 之间的值,第二列(col)必须是 0 到 9 之间的值。如果输入文件包含错误的格式,例如:

9 8
4 9
2 5
..

我想返回 2。但程序不返回 2,它在主函数结束时返回 0。

标签: creturn-value

解决方案


表达式(type < 0 && type > 4)总是错误的——一个数字不能既大于四又小于零。您应该使用 an||而不是&&那里:

if (read != 2 || type < 0 || type > 4 || col > 9) {

推荐阅读