如何在C++中将int连接到wchar_t*?

3

我需要创建并写入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*以创建不同名称的文件?

3个回答

3
您可以使用std::to_wstring:
#include <string>

// ...

std::wstring s = std::wstring("file_") + std::to_wstring(i) + std::wstring(".dat");

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

2
你可以使用 wstringstream
std::wstringstream wss;
wss << "nameFile" << i << ".txt";
uscita.open(wss.str().c_str(), ios::out);

这里实际上需要使用 wstringstream - Etienne de Martel
不对,它不能工作。编译器显示错误 C2664,无法将 'std :: basic_string <_Elem,_Traits,_Ax>' 转换为 'const wchar_t *'。 - DavideChicco.it
2
你需要使用.c_str(),更新答案。 - Joe

0

这样更简单、更快速:

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

只是一个警告。如果你不非常小心,sprintfwsprintf和其他类似函数很容易导致缓冲区溢出问题。(无论是现在还是以后代码维护时都可能发生。) - Michael Anderson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接