Let's say we have a C style string in C++ in the format [4 letters] [number] [number] ...
. For example, the string may look like:
abcd 1234 -6242 1212
It should be noted that the string is expected to have too much whitespace (as seen above).
How would I extract these three numbers and store them in an array?
Extract all integers from string in C++ The idea is to use stringstream:, objects of this class use a string buffer that contains a sequence of characters. Algorithm: Enter the whole string into stringstream. Extract the all words from string using loop.
A job for stringstreams, see it live: http://ideone.com/e8GjMg
#include <sstream>
#include <iostream>
int main()
{
std::istringstream iss(" abcd 1234 -6242 1212");
std::string s;
int a, b, c;
iss >> s >> a >> b >> c;
std::cout << s << " " << a << " " << b << " " << c << std::endl;
}
Prints
abcd 1234 -6242 1212
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