1

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;
2
  • 2
    Probably more a job for std..regex and std::stoi for the match. Commented Mar 22, 2016 at 22:33
  • @πάνταῥεῖ I guess it's just too complex for stringstream right? Commented Mar 22, 2016 at 22:35

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.