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?

Dani AI

Generated

A quick way to generalize this is to look for digit runs rather than only words that are all digits. As mrnutty’s token-by-token approach shows, splitting on whitespace works when numbers are isolated, but it will skip things like negative signs, punctuation next to numbers, or digits embedded in words. Also, when calling isdigit, prefer std::isdigit(static_cast<unsigned char>(c)) to avoid undefined behavior with non-ASCII bytes, and accumulate into a wider type (long long) to avoid overflow if the input is large.

C++ (matches signed integers anywhere in the text):

#include <string>
#include <regex>
#include <iostream>

int main() {
    std::string text = "mcDonalds car 456 burgerKing 8 clowns are scary money leeking from 56 my pockets I like turtles 1";
    std::regex re(R"(-?\d+)");
    long long sum = 0;

    for (std::sregex_iterator it(text.begin(), text.end(), re), end; it != end; ++it)
        sum += std::stoll(it->str()); // use stoll for wide range

    std::cout << "Total: " << sum << "\n";
}

Notes:

  • If you only want numbers that are standalone tokens (not inside words like abc123), tighten the pattern, e.g. std::regex re(R"((?<!\w)-?\d+(?!\w))");.
  • If you want to avoid exceptions, parse with std::from_chars on each match instead of std::stoll.

Python (concise and handles big ints automatically):

import re

text = "mcDonalds car 456 burgerKing 8 clowns are scary money leeking from 56 my pockets I like turtles 1"
nums = map(int, re.findall(r"-?\d+", text))
print("Total:", sum(nums))

You can adapt the regex to floats (e.g., r"-?\d+(?:\.\d+)?") or to require whole-token numbers by using word boundaries.

Recommended Answers

All 3 Replies

do your own homework

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;

}
commented: to the point, carefuly going through the steps in the code so even the most novice can understand +0

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.