Reading values from a string

Asked

Viewed 44 times

0

I just started studying c++ and I don’t 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 the sscanf, however I am 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 is 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);
  • 2

    tries to use inputs[x]. c_str()

  • It worked, thank you.

1 answer

1


The error indicates that sscanf has to receive a const char* as the first parameter and not a string how are you doing.

View the function signature sscanf:

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

To solve you can get the pointer to the character array of the string through 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.