Hi, I'm trying to find a way to extract numbers from a text consisting of words and numbers but have no idea how to do it. The numbers can be larger than one digit and should be able to be manipulated by common math operators like +, - and / after the extraction from the text. Should I go through the text as a string considering the numbers I want to extract is larger than one digit or as chars? And is it possible to turn the numbers to an int after I extracted them from the text so I can do math things with em?

like:
mcDonalds car 456 burgerKing 8 clowns are scary money leeking from 56 my pockets I like turtles 1


456, 8, 56, 1 I want to extract these numbers from the text and turn it into int so i can do something like this:

int value = 0;
loop{
value = value + extracted_number ;
}
cout << " The total value of the numbers is: " << value;

The total value of the numbers is: 521

I'm kind of new to programming and all..., you guys have any ideas?

Edited 7 Years Ago by timlo: n/a

By the example you gave us, this : "mcDonalds car 456 burgerKing 8
clowns are scary money leeking from 56 my pockets I like turtles 1".

I would suggest that you should extract the sentence word by word.
Then when you extract a word, you need to check if its a numeric by
using the isdigit function in cctype header file. If it is numeric, then
you can extract the data into a int variable and add it to the total sum.
Here is an example :

#include<iostream> //i.o
#include<cctype> //for isdigit
#include<sstream> //to phrase string
#include<string>

using namespace std;

//checks if a string is full of digits
bool isDigits(string word){
	for(unsigned int i = 0; i < word.size(); ++i){
		if(!isdigit(word[i])) return false;
	}	
	return true;
}
int main()
{
	string sentence = "what does 10 + 4 + 1 = ";
	stringstream extract; // extract words by words;

	extract << sentence; //enter the sentence that we want to extract word by word

	string word = "";

	int totalSum = 0;

	//while there are words to extract
	while(!extract.fail())
	{
		extract >> word; //extract the word

		if(isDigits(word)){//if the string is full of digits
			
			stringstream convert; //converts strings to ints
			convert << word; //insert the digits into our converter
			int theNumber = 0; //will hold the number inside the string
			
			//convert the string number into a int number and place it inside of theNumber variable
			convert >> theNumber; 

			//add the number to the total sum
			totalSum += theNumber;
		}

	}

	//display our results 

	cout << sentence << " " << totalSum << endl;

	return 0;

}
Comments
to the point, carefuly going through the steps in the code so even the most novice can understand

Thank you firstPerson! :)
I had no idea there was something called isdigit in fact i tried to look it up with the two books I've got and couldn't find it under cctype and the rest of the books.

This article has been dead for over six months. Start a new discussion instead.