In C++, I've got a string array variable called:

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

and an object which has this:

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

I would like to make a function which return an array, and after that i would like to call it something like this:

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

But i get this error:

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

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

有帮助吗?

解决方案 2

fileRows is an array of 500 elements. If you want to return the array so that you can later access the n-th element, you should return the pointer to the beginning of the array. For example:

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

Although it is probably better to use:

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

Using the first method, you can access the n-th element using:

data.filename()[n];

So, if you want to access the 5th element of the array you should use:

data.filename()[4];

On the other hand, the function MessageBox needs a const char *. So you must call the c_str() method to get the pointer:

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

其他提示

LPCSTR is nothing else but an alias for const char*. The problem is that the Data::fileName() returns a std::string object and there's no implicit conversion to const char*.

To retrieve a string from the std::string in form of const char*, use c_str() method , :

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

Also note that you have created an array of std::string objects:

string fileRows[500];

but in the Data::fileName() you're trying to return it as a single std::string object:

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

I recommend you to use std::vector instead of C-style array though.

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

No matter whether you will use std::vector or keep using an array, it will look like this:

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

std::string::c_str will give you a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) or LPCSTR

use std:string's function c_str() ... take a look at this answer

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top