Sign in to follow this  
Wukie

Learning C++(fstream question)

Recommended Posts

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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this