szu*_*rse 0 c++ arrays mfc stdstring lpcstr
在C++中,我有一个名为的字符串数组变量:
...
/* set the variable */
string fileRows[500];
...
/* fill the array with a file rows */
while ( getline(infile,sIn ) )
{
fileRows[i] = sIn;
i++;
}
Run Code Online (Sandbox Code Playgroud)
和一个具有以下内容的对象:
string Data::fileName(){
return (fileRows);
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个返回数组的函数,之后我想称之为:
Data name(hwnd);
MessageBox(hwnd, name.fileName(), "About", MB_OK);
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
不能将'std :: string*{aka std :: basic_string }'转换为'LPCSTR {aka const char }'以将参数'2'转换为'int MessageBoxA(HWND,LPCSTR,LPCSTR,UINT)'
如果我想显示数组的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);
Run Code Online (Sandbox Code Playgroud)
另请注意,您已创建了一个std::string对象数组:
string fileRows[500];
Run Code Online (Sandbox Code Playgroud)
但是在Data::fileName()你试图将它作为单个std::string对象返回时:
string Data::fileName() {
return fileRows;
}
Run Code Online (Sandbox Code Playgroud)
我建议你使用std::vector而不是C风格的数组.
如果我想显示数组的5.元素,如何转换它?
无论您是使用std::vector还是继续使用数组,它都将如下所示:
std::string Data::fileName() {
return fileRows[4];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
530 次 |
| 最近记录: |