Convert integer to formatted LPCWSTR. C ++

I have a direct3d project that uses D3DXCreateTextureFromFile () to load some images. This function accepts LPCWSTR for the file path. I want to load a series of textures that are numbered sequentially (i.e. MyImage0001.jpg, MyImage0002.jpg, etc.) But C ++ crazy lines confuse me.

How to make i:

for(int i=0; i < 3;i++) { //How do I convert i into a string path i can use with D3DXCreateTextureFromFile? } 

Edit:

I must mention that I am using the Visual Studio 2008 compiler

+4
source share
4 answers

One std::swprintf :

 wchar_t buffer[256]; std::swprintf(buffer, sizeof(buffer) / sizeof(*buffer), L"MyImage%04d.jpg", i); 

You can also use std::wstringstream :

 std::wstringstream ws; ws << L"MyImage" << std::setw(4) << std::setfill(L'0') << i << L".jpg"; ws.str().c_str(); // get the underlying text array 
+9
source

The most "C ++" way is to use wstringstream :

 #include <sstream> //... std::wstringstream ss; ss << 3; LPCWSTR str = ss.str().c_str(); 
+3
source

The Win32 API has several string formatting functions, for example:

wsprintf () :

 WCHAR buffer[SomeMaxLengthHere]; for(int i=0; i < 3;i++) { wsprintfW(buffer, L"%i", i); ... } 

StringCbPrintf () :

 WCHAR buffer[SomeMaxLengthHere]; for(int i=0; i < 3;i++) { StringCbPrintfW(buffer, sizeof(buffer), L"%i", I); ... } 

StringCchPrintf () :

 WCHAR buffer[SomeMaxLengthHere]; for(int i=0; i < 3;i++) { StringCchPrintfW(buffer, sizeof(buffer) / sizeof(WCHAR), L"%i", i); ... } 

Just to name a few.

+1
source

wsprintf

 /* wsprintf example */ #include <stdio.h> int main () { wchar_t buffer [50]; for(int i=0; i < 3;i++){ wsprintf (buffer, L"File%d.jpg", i); // buffer now contains the file1.jpg, then file2.jpg etc } return 0; } 
0
source

Source: https://habr.com/ru/post/1308949/


All Articles