如何在 C++ 中将变量附加到输出文件的名称中

How to append a variable in to the output file's name in C++

本文关键字:文件 输出 C++ 变量      更新时间:2023-10-16

我有一个C++项目,它将数据输出到文件中。以下是它的代码。

case 3:
            {
                outfile.open("price-change.csv");
                if(! outfile)
                {
                    cout << "Can not open outfile" << endl;
                    exit(1);
                }

我想将文件名更改为price-change-2014-12-23,其中2014-12-23是添加到文件名的变量,价格更改。你们知道吗?提前谢谢。

std::string filename = "price-change-" + datestring + ".csv"
outfile.open(filename);

应该这样做。

Thomas Matthews在评论中指出,较旧的编译器和没有启用C++11支持的编译器必须使用const char *而不是std::string打开文件。如果以上产生错误消息,并且C++11无法使用,请使用打开文件

outfile.open(filename.c_str());

如果涉及整数或浮点等数字,则可以使用字符串流轻松构建日期字符串。