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

我与影子孤独终老i 提交于 2019-12-22 01:15:13

问题


So me and my groupmates suddenly have some clutchwork at hand. I was assigned of making an import function that reads through a textfile that looks like this, and store it to a 2D array:

The columns are Tab-separated. As this suddenly came up, dont have the entire project file with me and I am nowhere near my old reliables, I tried conjuring this up in the most generic way possible:

void signal::import_data(string filename){
    ifstream file;

    file.open(filename.c_str());

    if(file.fail()){
        cerr << "file open fail" << endl;
    }else{
        while(!file.eof)
        {
            for(int j = 0; j < NumCols; j++){
                for(int i = 0; i < NumRows; i++){
                    file >> _data[j][i];
                }
            }
        }
    }
    file.close();
}

Am I doing this correct? Im not so sure if streaming like this can bypass tabs, or can it?


回答1:


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:

  • What's preferred pattern for reading lines from a file in C++?
  • Why is iostream::eof inside a loop condition considered wrong?


来源:https://stackoverflow.com/questions/14539200/c-read-txt-contents-and-store-into-2d-array

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