Question

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?

Was it helpful?

Solution

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!
}

OTHER TIPS

Write parser based on finite state machine and correct any input as you wish:

int extract_int_from_string(const char* s) {
   const char* h = s;
   while( *h ) {
      if( isdigit(*h) )
         return atoi(h);
      h+=1;
   }
   return 0;

} ... int i = extract_int_from_string("hello 100");

 //You can use the following function to get the integer part in your string...
    string findDigits(string s){
    string digits="";
    int len=s.length();
    for(int i=0;i<len;i++){
        if(s.at(i)>='0' && s.at(i)<='9')
        digits+=s[i];}
     return digits;}

// and call the above function inside this function below...
    int string_to_int(string s){
    string digits=findDigits(s);
    stringstream ss(digits);
    int x;
    ss >> x;
    return x;}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top