Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all integers from string c++

I need some help with getting all the integers from a std::string and getting each of those integer into an int variable.

String example:

<blah> hi 153 67 216

I would like the program to ignore the "blah" and "hi" and store each of the integers into an int variable. So it comes out to be like:

a = 153
b = 67
c = 216

Then i can freely print each separately like:

printf("First int: %d", a);
printf("Second int: %d", b);
printf("Third int: %d", c);

Thanks!

like image 980
Mike Avatar asked Dec 27 '22 01:12

Mike


1 Answers

You can create your own function that manipulates a std::ctype facet by using its scan_is method. Then you can return the generated string to a stringstream object and insert the contents to your integers:

#include <iostream>
#include <locale>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <cstring>

std::string extract_ints(std::ctype_base::mask category, std::string str, std::ctype<char> const& facet)
{
    using std::strlen;

    char const *begin = &str.front(),
               *end   = &str.back();

    auto res = facet.scan_is(category, begin, end);

    begin = &res[0];
    end   = &res[strlen(res)];

    return std::string(begin, end);
}

std::string extract_ints(std::string str)
{
    return extract_ints(std::ctype_base::digit, str,
         std::use_facet<std::ctype<char>>(std::locale("")));
}

int main()
{
    int a, b, c;

    std::string str = "abc 1 2 3";
    std::stringstream ss(extract_ints(str));

    ss >> a >> b >> c;

    std::cout << a << '\n' << b << '\n' << c;
}

Output:

1 2 3

Demo

like image 195
David G Avatar answered Jan 11 '23 01:01

David G