1
下面的代码使用日期命名文本文件,并将在命令提示符处输入的内容写入到.txt文件中。问题是,一旦我第二次运行代码,它将擦除之前写入的内容并写入新输入的代码。如果文本文件已经存在,我想保留以前编写的内容,跳下两行并添加新材料。有任何想法吗?C++将字符串添加到现有文本文件
#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";
}
}
http:// www。 cplusplus.com/reference/fstream/ofstream/ofstream/ – 2014-10-01 19:43:16
['std :: ios :: app'](http://en.cppreference.com/w/cpp/io/ios_base/openmode) – 2014-10-01 19:47:49
工作完美!任何想法如何删除写入的地址? – 2014-10-01 20:03:13