Dandy Dandy - 4 months ago 14
C++ Question

Streaming in and out a text file in C++

Basically, I'm trying to stream in a text file and stream out THE SAME information to another text file.

However, it's giving me weird new lines.

Example txt to test:

testing this is a test to see if this actually works

hopefully!
test



test

test


This is the output it gives me after testing:

testing this is a test to see if this actually works
hopefully!test


test
test


I want the output to be the same as the input. But I'm not sure what I'm doing wrong. Been stuck on this for a few hours now, lol.

Here is my code:

string input, name, content;
cout << "Enter input name and extension (Example: hi.txt)\n";
cin >> input;

ifstream file (input.c_str());

if (file.is_open()) {
cout << "Enter output name and extension (Example: hi2.txt)\n";
cin >> name;

ofstream output(name.c_str());

while (getline(file, content)) {
output << content;

if (content == "") {
output << "\n";
}
}
}

Answer

std::getline ignores the delimiter, which by default is \n when it reads a line. So, when it reads

testing this is a test to see if this actually works\n

content will actually be

testing this is a test to see if this actually works

Note the missing newline. That's why there is one new line missing after every line :)

You have to add that discarded delimiter:

output << content << '\n'; //Adds the discarded '\n' delimiter