Jump to content
  • Advertisement
Sign in to follow this  
Wukie

Learning C++(fstream question)

This topic is 4984 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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".

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!