2014-10-01 100 views
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"; 
    } 
} 
+0

http:// www。 cplusplus.com/reference/fstream/ofstream/ofstream/ – 2014-10-01 19:43:16

+1

['std :: ios :: app'](http://en.cppreference.com/w/cpp/io/ios_base/openmode) – 2014-10-01 19:47:49

+0

工作完美!任何想法如何删除写入的地址? – 2014-10-01 20:03:13

回答

2

更改

std::ofstream notes(m + d + y + ".txt", std::ios::out); 

对于

std::ofstream notes(m + d + y + ".txt", std::ios::app); 

这样,您将在文件

的末尾添加新行欲了解更多信息的写入方式:Check this link

+0

这样做!谢谢! – 2014-10-01 20:04:10

相关问题