How to concat an int to a wchar_t* in C++?

爷,独闯天下 提交于 2019-12-10 18:38:32

问题


I have to create and write on N files, everyone must have an integer ending to identificate it.

This is my piece of code:

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

And that's what I would like to find in my directory after execution:

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

The problem of the above code is that I get the compilin' error:

error C2110: '+' Impossible to add two pointers

If I try to create a string for the name, another problem comes in:

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

And the problem is:

error C2664: you cannot convert from string to const wchar_t*

What can I do? How can I create files with different names concating int to wchar_t*?


回答1:


You can use a wstringstream

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



回答2:


You can use std::to_wstring:

#include <string>

// ...

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

(Then use s.c_str() if you need a C-style wchar_t*.)




回答3:


That is easier and faster:

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


来源:https://stackoverflow.com/questions/8609842/how-to-concat-an-int-to-a-wchar-t-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!