ijustwantedtosayhi
ijustwantedtosayhi

Reputation: 29

C++ - Fstream not generating a new line

I have searched through a lot of questions on this website which are pretty much the same, but nothing works for me. In the first place, let me tell you that I am using Code::Blocks and I am using Ubuntu. This is my code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream file("code.out");

    string write;
    getline(cin, write);
    file << write << "\n";
    file.close();
}

Tried \n, tried \r\n (\r doesn't seem to do anything for me really). Oh and by the way, if you could also make it work with word-by-word reading that would be great. Thank you very much!

EDIT: Hey guys, I solved it. Thanks for the answers tho! I needed to add a ios::app after code.out!

Upvotes: 1

Views: 1369

Answers (3)

Dean Knight
Dean Knight

Reputation: 680

Try this code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    fstream file("code.out", std::fstream::out);

    string write;
    getline(cin, write);
    file << write << '\n';
    file.close();
}

Explicitly passing the std::fstream::out through the constructor got it to behave correctly for me and produced the newline.

Edit:

Note for future reference, my solution produces the newline but this will overwrite data currently found in the file. Ed Heal has code for appending to a file in his answer.

Adding

std::fstream::app

to my code would then mimic Ed Helms solution. Please mark his answer if appending functionality is actually what you needed. This answer will be for others who have a similar newline issue who want to overwrite the file.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60007

Should you be using ofstream. http://www.cplusplus.com/reference/fstream/ofstream/

Then check that it has opened.

Then check you have read some data - debugger is handy for that

EDIT

You need

 ofstream file("code.out", ios::out | ios::app)

Upvotes: 2

MazzMan
MazzMan

Reputation: 855

I also had that problem once.

Try using ofstream instead of fstream. Maby that'll help, because I used that too.

Upvotes: -1

Related Questions