I'm having a problem with putting newlines to text files. Using this example I found:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <fstream>
usingnamespace std;
int main()
{
ofstream fout;
fout.open("MyFile.txt");
fout << "This is line 1.\n"; //it ignores the \n here.
fout << "This is line 2." << endl; //it also ignores endl here.
fout << "This is line 3." << endl; //it only puts a newline right here.
fout.close();
return 0;
}
I noticed that it's only putting newlines at the end of the file as noted by the comments above. If I added an extra endl or '\n' on the third line, it would still have 1 newline at the end. If I removed the endl from the third line, it would not put a newline.
Whoops, didn't mean to put the semicolons there, fixed. I merged lines 10 and 11 to 9 (removing the semicolons from 9 and 10 and fout from 10 and 11.) and it still only placed a new line at the end. I also tried '\t' once before and that worked with no problems. It only seems to be endl and '\n' giving me problems.
My guess is that you are using a Windows text editor to view the text file. On Windows \r\n is often expected to mark new line and many windows text editors such as Notepad will ignore an alone \n.
Normally \n is automatically changed to \r\n behind the scenes when you write a text file so it's a bit strange if not \n is replaced by \r\n. Can you check your file in a hex editor to see if the \r is in there or not?
My guess is that you are using a Windows text editor to view the text file. On Windows \r\n is often expected to mark new line and many windows text editors such as Notepad will ignore an alone \n.
Normally \n is automatically changed to \r\n behind the scenes when you write a text file so it's a bit strange if not \n is replaced by \r\n. Can you check your file in a hex editor to see if the \r is in there or not?
Yeah I was looking at it through Notepad. I checked the original file with a hex editor and saw it only had \n. After changing it to \r\n the new lines showed up in notepad, and they showed up in the hex editor too. Thank you.