What's preferred pattern for reading lines from a file in C++?

后端 未结 5 997
深忆病人
深忆病人 2020-12-01 09:40

I\'ve seen at least two ways of reading lines from a file in C++ tutorials:

std::ifstream fs(\"myfile.txt\");
if (fs.is_open()) {
  while (fs.good()) {
    s         


        
5条回答
  •  死守一世寂寞
    2020-12-01 10:13

    Actually I prefer another way

    for (;;)
    {
      std::string line;
      if (!getline(myFile, line))
        break;
      ...
    }
    

    To me it reads better, and the string is scoped correctly (i.e. inside the loop where it is being used, not outside the loop)

    But of the two you've written the second is correct.

提交回复
热议问题