Search code examples
c++

Extract data from c++ string


I wanted to extract the values from the string in C++. I guess this is not the C++ way of doing this, but that one in particular doesn't work. Any ideas?

string line = "{10}{20}Hello World!";
int start;
int end;
string text;

// What to use here? Is the sscanf() a good idea? How to implement it?

cout << start; // 10
cout << end; // 20
cout << text; // Hello World!

Solution

  • Although you can make sscanf work, this solution is more appropriate for C programs. In C++ you should prefer string stream:

    string s("{10}{20}Hello World!");
    stringstream iss(s);
    

    Now you can use the familiar stream operations for reading input into integers and strings:

    string a;
    int x, y;
    iss.ignore(1, '{');
    iss >> x;
    iss.ignore(1, '}');
    iss.ignore(1, '{');
    iss >> y;
    iss.ignore(1, '}');
    getline(iss, a);
    

    Demo.