2010-05-06 61 views
4

我有一個direct3d項目,使用D3DXCreateTextureFromFile()加載一些圖像。該函數爲文件路徑提供LPCWSTR。我想加載一系列連續編號的紋理(即MyImage0001.jpg,MyImage0002.jpg等),但C++的瘋狂字符串讓我困惑。將整數轉換爲格式化的LPCWSTR。 C++

我該怎麼辦:

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

編輯:

我要提到我使用Visual Studio 2008的編譯器

回答

9

一種選擇是std::swprintf

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

你也可以使用一個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 
+1

+1:比我的好。 – 2010-05-06 01:00:16

+0

這工作,除了我需要前綴L「MyImage ....」 – 2010-05-06 01:05:29

+0

@MrBell - 謝謝,我忘了那個重要的細節。 – 2010-05-06 01:08:27

0

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; 
} 
+1

這不會產生寬字符串,但這個想法是好的,可以轉換爲'wsprintf'。 – 2010-05-06 05:31:17

3

最 'C++' 的方式是使用wstringstream

#include <sstream> 

//... 

std::wstringstream ss; 
ss << 3; 
LPCWSTR str = ss.str().c_str(); 
+1

對於stringstream的你需要做'ss.str()。c_str();' – 2010-05-06 01:05:18

+1

ya同時修復 – 2010-05-06 01:05:51

1

的Win32 API中有多個字符串格式化功能可用,例如:

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); 
    ... 
} 

只是僅舉幾例。