Reading values from a string

0

I started to study c ++ now and I do not quite understand it yet. I need to get a lot of information on each line of a string vector, so I thought I'd use sscanf , however I'm getting the following error:

In function ‘int main()’:
error: cannot convert ‘__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> > >::value_type {aka std::__cxx11::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘int sscanf(const char*, const char*, ...)’
   sscanf(inputs[0], "%d %d", &n, &m);
                                    ^
error: cannot convert ‘__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> > >::value_type {aka std::__cxx11::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘int sscanf(const char*, const char*, ...)’
   sscanf(inputs[1], "%d %d %d", &x, &y, &z);

My code looks like this:

int n, m, x, y, z;
vector<string> inputs;
string read;
while (1){
    getline(cin, read);
    if(!read.compare("0 0"))
        break;
    inputs.push_back(read);
}
sscanf(inputs[0], "%d %d", &n, &m);
sscanf(inputs[1], "%d %d %d", &x, &y, &z);
    
asked by anonymous 15.02.2018 / 15:18

1 answer

1

The error tells you that sscanf must receive const char* as the first parameter and not a string as it is passing.

See the sscanf signature:

int sscanf ( const char * s, const char * format, ...);
//-------------^

To resolve you can get the pointer to the character array of string through the function c_str :

sscanf(inputs[0].c_str(), "%d %d", &n, &m);
//---------------^aqui
sscanf(inputs[1].c_str(), "%d %d %d", &x, &y, &z);

See this example in Ideone

    
15.02.2018 / 15:33