Writing carriage returns to files

closed account (Gz64jE8b)
How can I do as the title says; everything that's written to the file appears on one line.

Also how can I give the file I'm opening a user-defined file name instead of pre-defined.

Example:

Instead of:
 
myfile.open("Newfile.txt");


This:

1
2
cin >> filename;
myfile.open(filename); // This gives me errors when I compile. 
http://cplusplus.com/reference/iostream/manipulators/endl/ or '\n'

¿What errors are you getting?
Try this
1
2
3
char filename[20];
cin >> filename;
myfile.open(filename);
closed account (Gz64jE8b)
Chriscpp, your suggestion worked perfectly, thank you.

ne555, please read the question before posting; you obviously misunderstood.
I'm confused. I don't see how Chriscpp's answer has anything to do with your question, and ne555's answer seems to be directly on point.

EDIT:

Also I don't recommend this:

1
2
char filename[20];
cin >> filename;  // if the user enters a string longer than 19 characters, you just corrupted memory 


If you need a string, you're better off with a string:

1
2
3
string filename;
cin >> filename;  // now a user can enter any length and you'll be OK
myfile.open(filename.c_str());
Last edited on
closed account (Gz64jE8b)
1
2
file << "abc";
file << "xyz";


When I open the file I see 'abcxyz' - it's all on one line.

I want it to appear like:

abc
xyz
file << "abc" << endl << "xyz";
Right. Or: file <<"abc\nxyz";
closed account (Gz64jE8b)
So you can send an endl to a file.

ne555 should've said that in the first place.

Thanks all.
ne555 should've said that in the first place.

It's obvious if you know that an ofstream is an ostream (which you can easily guess).
Also, endl is an '\n' + flush, so you should avoid it when you don't need to flush the stream.
closed account (Gz64jE8b)
Well I'm still just a beginner and the reference he posted only shows cout << endl;
Mohammed Abdul don't edit your post to another question, post a new topic.It is confusing.
Topic archived. No new replies allowed.