c++arraysmfcstdstringlpcstr

How to retrieve the specific element from an array of std::strings as a LPCSTR?


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?


Solution

  • 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);