0

I am using this code fragment to read all content from a file to a string:

fstream file;
file.open("text.txt");
while(!file.eof()){
    file >> line;
    code += line;
}
file.close();

By trial and error I've been trying to put noskipws in different places but had no luck so far. the content of my file is: 87HBE MEHB4, which is Hello World encoded by Vigenere.

Where should I put noskipws or is there another elegant solution for this simple problem?

  • 4
    Try this instead [`while(std::getline(file, line)) { /* process line */ }`](https://en.cppreference.com/w/cpp/string/basic_string/getline). Checking `eof` in the `while` condition is probably not what you want because the check isn't directly after the read, and using `>>` to read into a `string` is specifically intended to be whitespace-delimited, so not what you want. – BoBTFish Jul 18 '18 at 06:30
  • 5
    1) [Why is iostream::eof inside a loop condition considered wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) 2) [`std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline)? – Algirdas Preidžius Jul 18 '18 at 06:30
  • 1
    Additionally: I, personally, don't agree with the dup choice. While the use of `eof` might be wrong, it isn't the cause of the issues OP is having. – Algirdas Preidžius Jul 18 '18 at 06:36
  • @AlgirdasPreidžius Thanks, but yeah, BoBTFish and You were right, get line did get the job done. – Never Lucky Jul 18 '18 at 06:38

0 Answers0