所以我想在一个文件中输入一些东西,但它似乎不起作用。我的代码是:
ofstream f("reservedTables.DAT");
cin >> table;
f.open("reservedTables.DAT", ios::out | ios::app);
f << table;
f.close();我做错了什么?我为变量table写了数字,但它没有出现在我放入的文件中
发布于 2017-03-19 00:33:24
快速浏览:
ofstream f("reservedTables.DAT"); 分配流并打开文件。
cin >> table;读取来自用户的输入。
f.open("reservedTables.DAT", ios::out | ios::app);尝试重新打开文件。都会失败。
f << table;打开失败后,流处于失败状态,无法写入。
f.close();关闭文件。
解决方案
仅打开文件一次并检查错误。
ofstream f("reservedTables.DAT", ios::app); // no need for ios::out.
// Implied by o in ofstream
cin >> table;
if (f.is_open()) // make sure file opened before writing
{
if (!f << table) // make sure file wrote
{
std::cerr << "Oh snap. Failed write".
}
f.close(); // may not be needed. f will automatically close when it
// goes out of scope
}
else
{
std::cerr << "Oh snap. Failed open".
}发布于 2017-03-19 00:31:21
这是因为您要打开该文件两次。
如果调用open,实际上就是在调用rdbuf()->open(filename, mode | ios_base::out)。请注意(ref):
如果关联的文件已经打开,则立即返回空指针。
因为返回了一个空指针,所以它被分配给内部文件缓冲区,并且不再打开任何文件。这意味着任何写入它的尝试都会失败。
如果您指定了文件名,则构造函数已经打开了该文件,因此您不需要调用open
std::ofstream f("reservedTables.DAT");
std::cin >> table;
f << table;
f.close();https://stackoverflow.com/questions/42876885
复制相似问题