C++ file problem with endl; and "\n"?

Hello everyone,

When I try to make another line in a file using endl; or "\n" it does not work. I don't think it's a problem with my code because I copied and pasted an example from Cplusplus.com it did not work either.

example I used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  // writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}


The example .txt file is supposed to read:
"This is a line."
"This is another line."

Instead I get:
This is a line. This is another line.
I am using cygwin to compile.
How do I fix this?
Last edited on
> I am using cygwin to compile.
> How do I fix this?

There is nothing to fix. Line endings in Unix and Windows are different; your cygwin mounts are using Unix line endings.

After running your program, at the cygwin shell prompt, type in cat example.txt and you would see two lines in the output. If you want to view the file in a windows text editor, use Wordpad (it handles Unix line endings) and you would see two lines of text.
Topic archived. No new replies allowed.