首页 > 解决方案 > 如何在 C++ 中将名称文件设置为变量?

问题描述

如何将“dt”变量设置为文件名?

time_t now = time(0);
string dt = ctime(&now);


ofstream file;
file.open( ??? );

我正在尝试将 dt 设置为名称

标签: c++

解决方案


从 C++11 开始,您可以简单地传递stringas 参数:file.open(dt);.

在此之前,您必须传递一个const char*as 参数:file.open(dt.c_str());.

https://en.cppreference.com/w/cpp/io/basic_ofstream/open

您也可以直接使用构造函数:ofstream file(dt);ofstream file(dt.c_str());在 C++11 之前。

https://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream


推荐阅读