下面的代码生成一个以日期为标题的文本文件,并将在命令提示符下输入的内容写入 .txt。问题是,一旦我第二次运行代码,它会删除之前写入的内容并写入新输入的内容。如果文本文件已经存在,我想保留之前写的内容,跳下两行添加新的 Material 。有什么想法吗?
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
void main()
{
time_t now = time(0);
tm *ltm = localtime(&now);
int day = ltm->tm_mday;
int month = 1 + ltm->tm_mon;
int year = 1900 + ltm->tm_year;
std::string d = std::to_string(day);
std::string m = std::to_string(month);
std::string y = std::to_string(year);
std::string info;
std::getline (std::cin, info);
std::ofstream notes(m + d + y + ".txt", std::ios::out);
if (notes.is_open())
{
notes << info;
}
else
{
std::cout << "couldn't make file";
}
}
最佳答案
改变你的
std::ofstream notes(m + d + y + ".txt", std::ios::out);
为了
std::ofstream notes(m + d + y + ".txt", std::ios::app);
这样你就可以在文件末尾追加新行
有关写入模式的更多信息:Check this link
关于C++ 将字符串添加到现有文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149245/