简体   繁体   中英

C++ file writing - not writing variables as expected

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.

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", ie newline, tabs etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM