Learning C++(fstream question)

Started by
2 comments, last by Wukie 19 years, 4 months ago
Hey everyone! I'm going through the book Thinking in C++ which is a great book. I do have a question though about ifstream - ofstream.

#include <string>
#include <fstream>
using namespace std;

int main() {
  ifstream in("Scopy.cpp"); // Open for reading
  ofstream out("Scopy2.cpp"); // Open for writing
  string s;
  while(getline(in, s)) // Discards newline char
    out << s << "\n"; // ... must add it back
}
I understand the while(getline(in, s)) line. If I am correct it reads the line to the \n. But when you copy it to the new file it doesnt add the \n, so you add it manually, correct? But in this code it copies the whole file into a string, and thats where I'm stumped.

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

int main() {
  ifstream in("FillString.cpp");
  string s, line;
  while(getline(in, line))
    s += line + "\n";
  cout << s;
}
The line s += line + "\n"; confuses me. Is it basically saying that s = line including \n? Which allows it to read the whole file? If someone could clear this up for me I would appreciate it. Thanks!
Advertisement
Quote:I understand the while(getline(in, s)) line. If I am correct it reads the line to the \n. But when you copy it to the new file it doesnt add the \n, so you add it manually, correct?


Correct.

Quote:The line s += line + "\n"; confuses me. Is it basically saying that s = line including \n? Which allows it to read the whole file?


s += line + "\n"; is equivalent to s = s + line + "\n";. The += operator has been overloaded for strings to mean "append".
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
The += operator is shorthand for x = x +, so s += line + "\n"; is the same as s = s + line + "\n";. Basically, take whatever was in s, add whatever is in line and bung a "\n" on the end and stuff the result back into s.

Enigma
I see. Thank you very much for clearing that up.

This topic is closed to new replies.

Advertisement