如何测试以查看数组元素是否为空?

时间:2017-02-08 06:24:22

标签: c++ arrays pointers testing null

为了简化它,我需要从文件中读取数字并将它们存储在2D数组中。然后我必须检查以确保文件中有足够的数字来填充数组。

文件中的前两个数字是声明数组应该有多少行和列的数字。

我正在努力的部分是文件中的数字也可以包含0。

我正在使用此方法来测试元素是否为空

double numbers[MAX_ROW][MAX_COL];

for(int i = 0; i <= row; i++) {

    for(int n = 0; n <= col; n++) {

        if(!numbers[i][n]){
            cout << "Error: There is not enough data found file :(...." << endl;
            cout << "The Program will now exit....." << endl;

            return 0;
        }

    }
}

但后来我意识到,如果文件包含数字0,程序将退出。这是我不想发生的事情。

我也尝试使用指针并测试NULL但是这给了我一个关于(NULL和非指针之间的比较)的警告,它仍然会做同样的事情,如果文件中有一个0它只会退出。

double (*ptrNumbers)[MAX_COL] = numbers;


for(int i = 0; i <= row; i++) {

    for(int n = 0; n <= col; n++) {

        if(ptrNumbers[i][n] == NULL){
            cout << "Error: There is not enough data found file :(...." << endl;
            cout << "The Program will now exit....." << endl;

            return 0;
        }

    }
}

示例文件:

这个工作正常

   3    3
   1    3   4
   3    2   4
   3    5   2

由于文件中的零

,这不起作用
   3    3
   1    3   4
   3    0   4
   3    5   2

这是我想要测试的错误类型。 它说有3行3列但是没有数字来填充数组的其余部分。因此,它们将初始化为0,因为您可以得出结论也会导致同样的问题。

   3    3
   1    3   4
   3    2   4
   3    

任何人都知道如何测试&#34;空&#34;元素但不包含0的元素??或者我只是做错了什么?

提前感谢您的任何帮助:)

我从以前的建议中改变了我的程序。

如果文件中没有足够的数字,我设置了bool函数来返回false语句。但是,即使文件具有正确的数字量,文件仍将执行if语句并返回false值。我的语法在某种程度上是错误的吗?

for(int i = 0; i <= row; i++) {

    for(int n = 0; n <= col; n++) {

        if(!(inFile >> numbers[i][n])) {

            return false;
        }
        else {
            inFile >> numArray[i][n];

        }


    }
}
return true;

1 个答案:

答案 0 :(得分:1)

在阅读文件内容时必须捕获错误。

std::ifstream ifile("The input file");
ifile >> row >> col;
for(int i = 0; i <= row; i++) {
   for(int n = 0; n <= col; n++) {
      if( ! (ifile >> ptrNumbers[i][n]))
      {
         // Problem reading the number.
         cout << "Error: There is not enough data found file :(...." << endl;
         cout << "The Program will now exit....." << endl;
      }
   }
}

<强>更新

更新的功能有问题。

for(int i = 0; i <= row; i++) {
    for(int n = 0; n <= col; n++) {
        if(!(inFile >> numbers[i][n])) {
            return false;
        }
        else {
            // You are now reading into the same element
            // of the array again.
            inFile >> numArray[i][n];
        }
    }
}
return true;

您不需要该功能中的else部分。

for(int i = 0; i <= row; i++) {
    for(int n = 0; n <= col; n++) {
        if(!(inFile >> numbers[i][n])) {
            return false;
        }
    }
}
return true;