【发布时间】:2015-05-10 05:38:11
【问题描述】:
我在 C++ 中的文件输出和输入一直存在问题。出于某种原因,我只是无法理解。但我有一个问题(是的,上课..我知道。我已经感觉很糟糕,但教授没有太多帮助)我正在为一个菜单工作。
这是我到目前为止所得到的。
void addName(){
string name;
ofstream outfile;
cout << "Please type a name you would like to add:";
outfile.open("file.txt", std::ios_base::app);
cin >> name;
outfile << name;
cout << "Name added!" << endl;
}
我把它称为我的main 东西。对不起我的业余爱好。
问题是如何将“名称”附加到我的file.txt?
截图:
【问题讨论】:
-
你的代码有效吗?
-
这很奇怪,它运行良好但实际上并没有将名称添加到文件中。 @DrewDormann
-
或者你正在查看错误的文件,也许。
-
尝试在关闭大括号之前调用 outfile.close()。
-
@MateuszKacprzak 不需要,析构函数会关闭文件。它编译并运行良好:ideone.com/mEJL27(在我的机器上运行正常)。检查你是否打开了正确的文件,做一个测试
if(!outfile) std::cout << "didn't open the file\n";