【问题标题】:How to concat an int to a wchar_t* in C++?如何在 C++ 中将 int 连接到 wchar_t*?
【发布时间】:2012-01-26 10:43:22
【问题描述】:

我要创建和写N个文件,每个人都必须有一个整数结尾来识别它。

这是我的一段代码:

for(int i=0; i<MAX; i++)
{
    uscita.open("nameFile"+i+".txt", ios::out); 
    uscita <<  getData() << endl;
    uscita.close();     
}

这就是我想在执行后在我的目录中找到的内容:

nameFile0.txt
nameFile1.txt
nameFile2.txt
...
nameFileMAX.txt

上面代码的问题是我得到了编译错误:

error C2110: '+' 无法添加两个指针

如果我尝试为名称创建一个字符串,则会出现另一个问题:

string s ="nameFile"+i+".txt";
uscita.open(s, ios::out); 

问题是:

错误 C2664:您无法从字符串转换为 const wchar_t*

我能做什么?如何创建将int 连接到wchar_t* 的不同名称的文件?

【问题讨论】:

    标签: c++ int wchar-t wchar


    【解决方案1】:

    您可以使用wstringstream

    std::wstringstream wss;
    wss << "nameFile" << i << ".txt";
    uscita.open(wss.str().c_str(), ios::out);
    

    【讨论】:

    • 实际上这里需要wstringstream
    • 不,它不起作用。编译器说:错误 C2664,不可能从 'std::basic_string<_elem>' 转换为 'const wchar_t *'
    • 你需要使用.c_str(),更新答案。
    【解决方案2】:

    你可以使用std::to_wstring:

    #include <string>
    
    // ...
    
    std::wstring s = std::wstring("file_") + std::to_wstring(i) + std::wstring(".dat");
    

    (如果需要 C 风格的 wchar_t*,请使用 s.c_str()。)

    【讨论】:

      【解决方案3】:

      这样更容易更快:

      wchar_t fn[16];
      wsprintf(fn, L"nameFile%d.txt", i);
      uscita.open(fn, ios::out);
      

      【讨论】:

      • 只是一个警告。如果您不真的小心,sprintfwsprintf 和朋友经常会导致缓冲区溢出。 (现在或以后维护代码时。)
      猜你喜欢
      • 2018-03-07
      • 2014-07-10
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2019-06-16
      相关资源
      最近更新 更多