c++ - 为什么我的程序在第一次运行时写入文件,但在以后运行同一程序时却没有?
问题描述
我正在尝试编写写入文件的代码。它适用于第一次运行,但对于以后的任何运行,它都不会将用户输入写入文件。为什么在创建写入文件后不写入文件?我有一个 if-else 语句来检查一个已经存在的文件。如果有一个文件,它应该写入它。否则,它会创建一个要写入的文件。
fstream advice("advice.txt", ios::in|ios::out);
advice.open("advice.txt");
if (!advice.fail())
{
cout << "Found advise file." << endl << "Old advice:" << endl;
while (getline(advice, line))
{
cout << line << endl;
}
advice.flush();
advice.close();
advice.open("advice.txt", ios::in|ios::out|ios::app);
}
else
{
cout << "Could not open the Advise file." << endl<<"Assumption: first run - creating a new file..."<<endl;
advice.flush();
advice.close();
advice.open("advice.txt", ios::in | ios::out | ios::trunc); //create new file
}
cout << "Enter your phrase for the next user." << endl;
getline(cin, line);
advice <<line << endl;
advice.flush();
advice.close();
return 0;
解决方案
推荐阅读
- python-3.x - 如何在神经机器翻译模型中使用 BERT
- python - 如何投影天气雷达二进制文件
- python - VScode 中导入 sql.connector 中的 ModuleNotFoundError
- javascript - TypeScript - 如果扩展其他东西,类泛型类型太窄,如果不扩展任何东西,则不是
- python - 如何在 django admin 中更改外键字段的大小?
- java - Java Scanner nextInt() 让我按两次 Enter 以使该值被接受
- typescript - Typescript 项目引用:处理引用项目的第三方依赖项
- python - python - 如何使用正则表达式替换字符串中的特定组?
- sql - 如何使用 windows 功能检索第一个日期和最后一个日期?
- kivy - KivyMD navdrawer 是透明的