C++ Rewrite a file but leaving out everything before a word

前端 未结 5 404
天涯浪人
天涯浪人 2020-12-17 01:25

I\'m using Visual C++ Express 2010... and I\'m very new to C++.

I want to read a file then remove everything before the word \"<--START-->\" and rewrite the file

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 02:20

    First of all, your while loop is wrong. In fact, such while loop is almost always wrong.

    You should be writing the loop as:

    while (myReadFile >> output) 
    {
         if (line > 20) {
             cout << output;
         }
         line++;
    }
    

    Your while(!myReadFile.eof()) loop is wrong, because the eof flag (or any other failure flag) is set after an attempt to read from the stream fails; that means, if the attempt to read fails, you're still outputting, because you're still inside the loop, and the rest of the code in the loop still executes when it in fact should not.

    In my version, however, if an attempt to read (i.e myReadFile >> output) fails, then returned std::istream& implicitly converts into false, and the loop exits immediately. And if it doesn't fail, the returned stream implicitly converts to true.

    By the way, it seems to me that you want to read line-by-line, instead of word-by-word. If so, then you should write this as:

    std::string sline; //this should be std::string
    while (std::getline(myReadFile, sline))
    {
         if (line > 20) {
             cout << sline;
         }
         line++;
    }
    

    Again std::getline returns std::istream. If the read was successful, the returned stream implicitly converts to true and the loop will continue, or if it was unsuccessful, then it would implicitly convert to false and the loop will exit.

提交回复
热议问题