如何在我的txt文件中写入并在下面附加文本

时间:2017-11-17 07:59:13

标签: c++ notepad

我似乎无法在.txt文件中显示输出。 我想将来在文本文件下面附加。

using namespace std;

int main()
{
    string month;
    int year;
    stringstream filename;

    cin >> month;
    cin >> year;

    filename << "Expenses_" << month << "_" << year << ".txt";
    ofstream myfile(filename.str()); 

    myfile.open(filename.str());
    myfile << "Hello World!";
    myfile.close();

    return 0;
}

2 个答案:

答案 0 :(得分:0)

将文件打开为:

std::ofstream myfile(filename.str(), std::ofstream::out | std::ofstream::app);

在创建ofstream对象时传递文件名也会打开该文件,您无需再次调用.open

答案 1 :(得分:0)

ofstream myfile(filename.str(), ofstream::out | ofstream::app);

构造函数会自动打开文件进行编写并将写入指针移动到文件的末尾,以便您可以附加到该文件。无需再次打开文件,因为std::ofstream(const char*, int) consturctor 已经为您打开了文件

替代方案是:

ofstream myfile;
myfile.open(filename.str(), ofstream::out | ofstream::app);
相关问题