Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Numbers from Mixed String using stringstream

Tags:

c++

I am trying to extract numbers from a string like Hello1234 using stringstream. I have written the code which works for extracting numbers when entered as apart from the string like:

Hello 1234 World 9876 Hello1234

gives 1234 9876 as output but it doesn't read the mixed string which has both string and number. How can we extract it? - For example: Hello1234 should give 1234.

Here is my code until now:

cout << "Welcome to the string stream program. " << endl;
    string string1;
    cout << "Enter a string with numbers and words: ";
    getline(cin, string1);

    stringstream ss; //intiazling string stream

    ss << string1;  //stores the string in stringstream 

    string temp;  //string for reading words
    int number;   //int for reading integers

    while(!ss.eof()) {
        ss >> temp;
        if (stringstream(temp) >> number) {
            cout << "A number found is: " << number << endl;
        }
    }
like image 955
waasss Avatar asked Dec 06 '25 05:12

waasss


1 Answers

If you're not limited to a solution that uses std::stringstream, I suggest you take a look at regular expressions. Example:

int main() {
    std::string s = "Hello 123 World 456 Hello789";    
    std::regex regex(R"(\d+)");   // matches a sequence of digits

    std::smatch match;
    while (std::regex_search(s, match, regex)) {
        std::cout << std::stoi(match.str()) << std::endl;
        s = match.suffix();
    }
}

The output:

123
456
789
like image 108
Evg Avatar answered Dec 08 '25 17:12

Evg