使用C Visual Studio中的循环写入不同的文件名

writing to different file names using for loop in C++ visual studio

本文关键字:文件名 循环 Visual Studio 使用      更新时间:2023-10-16

我正在尝试将一些数据写入每个索引的不同文件。即,文件名应该从datafile0.res更改为datafile99.res。取决于传递的索引。

我正在使用Visual C 2008。

代码是:

void write_data(int index) {
ofstream coutput;
// first i need to convert integer index to string. Not sure if right?
ostringstream temp;
temp<<index;
std::string s = temp.str();
std::string dir = "C:My_Datadatafile" + s + ".res";
coutput.open(dir);

当我运行此代码时,出现以下错误:

error C2664: 'void std::basic_ofstream<_Elem,_Traits>::open(const wchar_t ,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::string' to 'const wchar_t *'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called.

请需要您的帮助。

预先感谢

这与您所陈述的目标或串联无关。

std::fstream::open,在C 11之前,需要const char*,而不是std::string

so:

coutput.open(dir.c_str());