Could anybody solve this program work for every input we give to extract them and printing them by using vectors and string stream.
I am succeeded in obtaining output if i have known size of input but i need it to work for unknown size of string. Thank you.
vector<int> parseInts(const string & str)
{
vector<int> d; // vector of integers.
stringstream ss(str); // stringstream, nitialise with str
string temp;
while ( ss >> temp ) // loop while a string can be extracted from ss
{
stringstream st(temp); // another stringstream, contains just one 'word'
while ( st ) // loop while status of stringstream is good
{
int i;
if (st >> i) // try to read an integer
d.push_back(i); // success, store it
else
{
st.clear(); // failed, so reset status flags
st.get(); // read and discard a single char
}
}
}
return d; // return result
}
The idea behind it, rightly or wrongly - because I still don't know what input you would like to accept, is to deal with a "word" like this:
fghd86g890g68d9g69dfg689dfhsd
and extract these integers:
86 890 68 9 69 689
Or a "word" like this: 3.14159 would result in these two integers.
3 14159
In the latter example, it first reads 3, stores it. Then tries to read another integer, but fails. So it instead discards one character (could also use the ignore() function), and tries again.