Kalie
Kalie

Reputation: 13

c++ extract an int from inside a string using stringstream

So I have the following string, line is it possible to extract the int that's inside?

I can use a very rudimentary regex expression but some stringstream solutions I found here look way cleaner and convert to type int.

string line = "            <li id="episode_275">"

I have the following code, but I don't know to deal with the rest of the string like: the 4 tab indent,the "

int value;
stringstream ss(line);
ss >> value;

Upvotes: 1

Views: 426

Answers (1)

Cameron
Cameron

Reputation: 98746

This can be done quite simply by just looking for the first digit, then having strtol do the integer parsing for you from that point:

#include <string>
#include <cctype>
#include <cstdlib>

int extractFirstIntInString(std::string const& s)
{
    for (std::size_t i = 0; i != s.size(); ++i)
        if (std::isdigit(s[i]))
            return std::strtol(s.c_str() + i, nullptr, 10);
    return 0;    // no integer in string
}

Upvotes: 1

Related Questions