I’ve written this code to extract numbers from a string using a string iterator.
The iterator picks up the first number and decides to call it a day.
Why’s it so?
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string myAge = "I am 23 years old";
string::iterator iterator;
char numberInCharacterForm;
string numberInStringForm;
stringstream convertToString;
for(iterator = myAge.begin();iterator!=myAge.end();iterator++)
{
numberInCharacterForm = *iterator;
if(numberInCharacterForm >= '0' & numberInCharacterForm <='9')
{
convertToString << numberInCharacterForm;
convertToString >> numberInStringForm;
}
}
cout << numberInStringForm <<endl;
getch();
return 0;
}
Output is 2;
Just collect the characters into the
stringstreamand print it afterwards:However there is no need for manual iteration over the string: