C++ No viable conversion from string to const char *

16,124

Do this:

hist->GetXaxis()->SetTitle(xlabel.c_str());
//                               ^^^^^^^^
Share:
16,124
khfrekek
Author by

khfrekek

Updated on July 20, 2022

Comments

  • khfrekek
    khfrekek almost 2 years

    I'm using C++ (using CERN's ROOT framework) and I'm having a little problem with strings. I'm trying to label a histogram axis using a string defined by the user earlier in the code. Here are the relevant parts of the code:

    string xlabel;
    
    ...
    cout << "Enter x-axis label:" << endl;
    getline(cin >> ws, xlabel);
    
    ...
    
    hist->GetXaxis()->SetTitle(xlabel);
    

    Where the last line is just syntax that ROOT uses (usually xlabel here would be in quotation marks and you can type in what you want the label to be, but I am trying to input the string defined earlier in the code.)

    Anyway, when I compile this, I get the following error:

    error: no viable conversion from 'string'
          (aka 'basic_string<char>') to 'const char *'
            hist->GetXaxis()->SetTitle(xlabel);
                                       ^~~~~~
    

    I have tried re-defining xlabel as a const char * but it didn't like that either. Does anyone have any suggestions on how I could define this string?

    Thanks in advance!

  • khfrekek
    khfrekek almost 9 years
    It worked! I just looked up what c_str() does and it makes total sense now. Thank you so much!