# Learning C++(fstream question)

## Recommended Posts

Wukie    122
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!

##### Share on other sites
Fruny    1658
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".

##### Share on other sites
Enigma    1410
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

##### Share on other sites
Wukie    122
I see. Thank you very much for clearing that up.