【问题标题】:writing to different file names using for loop in C++ visual studio在 C++ Visual Studio 中使用 for 循环写入不同的文件名
【发布时间】:2014-01-31 17:30:33
【问题描述】:

我正在尝试将一些数据写入每个索引的不同文件。即文件名应根据传递的索引从 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_Data\datafile" + 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.

请需要你的帮助。

提前致谢

【问题讨论】:

  • coutput.open(dir.c_str()); 阅读错误信息有时会有所帮助。
  • 这不仅与“写入不同的文件”或您声明的目标完全无关(甚至连接完全不相关),而且这也被问了很多次之前.

标签: c++ file-io ofstream


【解决方案1】:

这与您声明的目标或您的串联无关。

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

所以:

coutput.open(dir.c_str());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多