2013-03-13 31 views
0

在C++中, 我得叫一個字符串數組變量:如何從一個std :: strings數組中檢索特定元素作爲LPCSTR?

... 
/* set the variable */ 
string fileRows[500]; 
... 
/* fill the array with a file rows */ 
while (getline(infile,sIn)) 
{ 
    fileRows[i] = sIn; 
    i++; 
} 

,並具有這樣的一個對象:

string Data::fileName(){ 
    return (fileRows); 
} 

我想就其中返回一個數組的函數,從那以後,我想叫它是這樣的:

Data name(hwnd); 
MessageBox(hwnd, name.fileName(), "About", MB_OK); 

,但我得到這個錯誤:

cannot convert 'std::string* {aka std::basic_string}' to 'LPCSTR {aka const char}' for argument '2' to 'int MessageBoxA(HWND, LPCSTR, LPCSTR, UINT)'

如果我想顯示數組的5.元素,如何轉換它?

+4

'MessageBox(hwnd,name.fileName()。c_str(),「About」,MB_OK);'? – Blake 2013-03-13 21:44:43

+0

MessageBoxA的聲明是什麼? – 2013-03-13 21:46:28

回答

2

fileRows是500個元素的數組。如果要返回數組以便稍後可以訪問第n個元素,則應該將指針返回到數組的開頭。例如:

string* Data::fileName(){ 
     return fileRows; 
} 

雖然這可能是更好的使用:

const string& Data::getFileName(size_t index){ 
     return fileRows[index]; 
} 

使用第一種方法,您可以使用訪問第n個元素:

data.filename()[n]; 

所以,如果你想訪問你應該使用的第五個元素:

data.filename()[4]; 

另一方面,函數MessageBox需要一個const char *。因此,您必須調用c_str()方法來獲取指針:

Data name(hwnd); 
MessageBox(hwnd, name.fileName()[4].c_str(), "About", MB_OK); 
+0

非常感謝你的問題! :-) 謝謝! – David 2013-03-13 22:10:33

+0

-1'fileName [5]'不是第5個元素。 – LihO 2013-03-13 22:16:51

+0

@LihO你說得對,但我沒有說。無論如何,我會更新答案來澄清。 – 2013-03-13 22:24:10

5

LPCSTR只不過是const char*的別名。問題是Data::fileName()返回一個std::string對象,並且沒有隱式轉換爲const char*

要在const char*形式檢索來自std::string字符串,請使用c_str()方法:

MessageBox(hwnd, name.fileName().c_str(), "About", MB_OK); 

另外請注意,您所創建std::string對象的數組:

string fileRows[500]; 

但在Data::fileName()中,您試圖將其作爲單個std::string對象返回:

string Data::fileName() { 
    return fileRows; 
} 

雖然我建議您使用std::vector而不是C風格的數組。

If i would like to show the 5. element of the array, how to convert it?

不管你是否使用std::vector或繼續使用的陣列,它看起來就像這樣:

std::string Data::fileName() { 
    return fileRows[4]; 
} 
+2

'LPCSTR'是'char const *'。 : - ] – ildjarn 2013-03-13 21:46:54

+0

我得到這個錯誤: 錯誤:無法轉換'(std :: string *)(&((Data *)this) - > Data :: fileRows)'from'std :: string * {aka std :: basic_string *}'to'std :: string {aka std :: basic_string }' – David 2013-03-13 21:53:13

+0

@ildjarn:確實;) – LihO 2013-03-13 21:56:08

0

使用std:string的功能c_str() ...看看這個answer

1

std::string::c_str會給你一個指向一個數組的指針,該數組包含一個以空字符結尾的字符序列(即C字符串)或LPCSTR

相關問題