0

I have a file containing the sentence "Hallo, my name is Max". I have tried printing it on the Command Prompt, it printed "Hallo, my name is Max Max". What I don't understand is why did it print "Max" two times and not one?

#include<iostream>
#include<string>
#include<fstream>

int main(){
    std::string str;
    std::ifstream myfile("text.txt");
    while(myfile){
    myfile >> str;
    std::cout <<str<< " ";
    }
    myfile.close();
    return 0;
}
  • `while(myfile)` isn't the right way to detect end-of-file. – rustyx Mar 25 '18 at 19:08
  • Put the extraction operator in the loop condition, or else you will have the same problem as [this](https://stackoverflow.com/q/5605125/9254539), even though you're using the implicit conversion from a stream to bool instead of `eof()`. – BessieTheCookie Mar 25 '18 at 19:08
  • 1
    In case that's not obvious, testing for `EOF` is what you are doing in `while(myfile)`. – Baum mit Augen Mar 25 '18 at 19:08

0 Answers0