convert string to int use sstream

Amirhossein Mahdinejad picture Amirhossein Mahdinejad · Sep 21, 2013 · Viewed 10.4k times · Source

We want to convert string to int using sstream.

But we don't know our string has an integer or not, for example it can be the "hello 200" and we want 200 in that, or it can be "hello" and there was no solution!

I have this code when we have only an integer in the string:

inline int string_to_int(string s)
{
    stringstream ss(s);
    int x;
    ss >> x;
    return x;
}

Now, if s = "hello 200!" or s = "hello" , how we can do that?

Answer

masoud picture masoud · Sep 21, 2013

A simple possibility which ignores bad inputs until first integer in a string:

bool string_to_int(string str, int &x)
{
    istringstream ss(str);

    while (!ss.eof())
    {
       if (ss >> x)
           return true;

       ss.clear();
       ss.ignore();
    }
    return false; // There is no integer!
}