简体   繁体   English

C ++文件写入-不能按预期写入变量

[英]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. 我浏览了一些不同的内容(似乎无法在pluralrsight上找到一个好的文件I / O教程),并且在文件编写方面阅读了tutorialspoint和cplusplus网站,但我的似乎无法正常工作。

I copied rather similarly, the tutorial fro tutorialspoint on C++ file I/O: 我以类似的方式复制了有关c ++文件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. 奇怪的是,它在正确的位置创建了.txt文件,但其输出等于2个空行和破折号。 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 >> age;之后,您必须冲洗缓冲液cin >> age; ,

cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');

and change ios::ate to ios::app 并将ios::ate更改为ios::app

must #include <limits> 必须#include <limits>

ios:ate truncates the file, whereas ios::app appends at the end. ios:ate截断文件,而ios::app在末尾追加。

An alternative to cin.ignore is to use after cin >> age the getline as cin.ignore的替代cin.ignore是在cin >> agegetline cin >> age

getline(cin >> ws, inp);

This instructs the input stream to discard previously accumulated "whitespaces", ie newline, tabs etc 这指示输入流放弃先前累积的“空白”,即换行符,制表符等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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