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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With