C++: Read .txt contents and store into 2D array

穿精又带淫゛_ 提交于 2019-12-04 17:24:52
Nawaz

I think this code:

while(!file.eof)
{
   for(int j = 0; j < NumCols; j++){
       for(int i = 0; i < NumRows; i++){
              file >> _data[j][i];
      }
   }
}

should be replaced with this:

for(int j = 0; j < NumCols; j++)
{
   for(int i = 0; i < NumRows; i++)
   {
         if ( !(file >> _data[j][i]) ) 
         {
             std::cerr << "error while reading file";
             break;
         }
   }
   if ( !file ) break;
}

That is, if you expect NumCols * NumRows entries to be there in the file, why explicitly check for end of file? Let it read till you read NumCols * NumRows entries is read. Once it read, it will automatically exit from the loop.

But you must check if the file ends before NumCols * NumRows entries is read, which is why I'm doing this:

if ( !(file >> _data[j][i]) ) 
{
    std::cerr << "error while reading file";
    break;
}

If the file reaches eof character, OR some other read-failure before it finishes reading NumCols * NumRows entries, then the condition in the if would evaluate to true and it will print the error message and break the loop, it will break outer loop also, as the expression !file will evaluate to true.

For a detail explanation as to HOW TO read files using C++ streams, read the answers from these topics:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!