0

在 C++ 中,我有一个名为的字符串数组变量:

...
/* 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);

但我得到这个错误:

无法将参数 '2' 的 'std::string* {aka std::basic_string }' 转换为 'LPCSTR {aka const char }' 到 'int MessageBoxA(HWND, LPCSTR, LPCSTR, UINT)'

如果我想显示数组的 5. 元素,如何转换它?

4

4 回答 4

5

LPCSTR只不过是const char*. 问题是Data::fileName()返回一个std::string对象并且没有隐式转换为const char*.

要从 的std::string形式中检索字符串const char*,请使用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 样式的数组。

如果我想显示数组的 5. 元素,如何转换它?

无论您是使用std::vector还是继续使用数组,它都将如下所示:

std::string Data::fileName() {
    return fileRows[4];
}
于 2013-03-13T21:45:09.257 回答
2

fileRows 是一个包含 500 个元素的数组。如果要返回数组以便以后可以访问第 n 个元素,则应返回指向数组开头的指针。例如:

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

虽然使用它可能更好:

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

使用第一种方法,您可以使用以下方法访问第 n 个元素:

data.filename()[n];

所以,如果你想访问数组的第 5 个元素,你应该使用:

data.filename()[4];

另一方面,函数 MessageBox 需要一个 const char *。所以你必须调用 c_str() 方法来获取指针:

Data name(hwnd);
MessageBox(hwnd, name.fileName()[4].c_str(), "About", MB_OK);
于 2013-03-13T22:03:43.833 回答
1

std::string::c_str将为您提供指向包含以 null 结尾的字符序列(即 C 字符串)的数组的指针,或LPCSTR

于 2013-03-13T21:47:45.783 回答
0

usestd:string的功能c_str()...看看这个答案

于 2013-03-13T21:45:20.080 回答