Reputation: 1945
I've looked through a few different things (cant seem to find a good file i/o tutorial on pluralrsight), and I've read tutorialspoint and cplusplus websites on file writing but mine won't seem to work the same.
I copied rather similarly, the tutorial fro tutorialspoint on C++ file I/O:
ofstream out;
out.open("D:\\cpp_files\\test_iofile.txt", ios::out);
cout << "Writing to file" << endl;
cout << "Enter your name: ";
string name;
getline(cin, name);
out << name;
cout << "Enter age: ";
int age;
cin >> age;
out << age << endl << "This is an insert" << endl;
out.close();
There's some more stuff in the middle you probably don't care much about, and then there's this section:
out.open("D:\\cpp_files\\test_iofile.txt", ios::ate);
out << endl;
string inp;
cout << "Write some random crap: ";
getline(cin, inp);
out << inp << endl;
out << "-----------";
out.close();
The weird thing is, it creates the .txt file in the right location, but its output equates to 2 blank lines and the dashes. So I end up with (The '>' added to indicate blank lines):
>
>
----------
I know it must be something I am missing, but I can't seem to catch it. No build errors from the compiler either.
Upvotes: 0
Views: 118
Reputation: 56577
You have to flush the buffer after you cin >> age;
,
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
and change ios::ate
to ios::app
must #include <limits>
ios:ate
truncates the file, whereas ios::app
appends at the end.
An alternative to cin.ignore
is to use after cin >> age
the getline
as
getline(cin >> ws, inp);
This instructs the input stream to discard previously accumulated "whitespaces", i.e. newline, tabs etc
Upvotes: 1