C++: Everytime I read in by fstream I got 1 extra character at the end

前端 未结 2 505
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 20:52

Everytime I read in by fstream I got 1 extra character at the end, How can I avoid this?

EDIT:

ifstream readfile(inputFile);
ofstream writefile(outputFil         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-08 21:26

    This typically results from testing for the end of file incorrectly. You normally want to do something like:

    while (infile>>variable) ...
    

    or:

    while (std::getline(infile, whatever)) ...
    

    but NOT:

    while (infile.good()) ...
    

    or:

    while (!infile.eof()) ...
    

    Edit: The first two do a read, check whether it failed, and if so exit the loop. The latter two attempt a read, process what was "read", and then exit the loop on the next iteration if the previous attempt failed.

    Edit2: to copy one file to another easily, consider using something like this:

    // open the files:
    ifstream readfile(inputFile);
    ofstream writefile(outputFile);
    
    // do the copy:
    writefile << readfile.rdbuf();
    

提交回复
热议问题