Search code examples
c++stringostringstream

c++ extract just numbers from an ostringstream


If I have an ostringstream that contains various numbers separated by -

(That's: space - space btw)

Could I extract each number individually?


Solution

  • use one of spiting functions from here: Split a string in C++? storing them as strings inside std::vector, then use std::stoi (or equivalent) which parses string to integer , surrounding each call with try / catch.

    example (after splitting):

    for (int i = 0; i < arrayOfStrings.size(); i++)
    {
        try
        {
            int myInt = std::stoi(arrayOfStrings[i]);
        }
        catch (std::exception& e)
        {
            std::cout<<e.what()<<"\n";
        }
    }