Extract all integers from string in C++


Here we will see how to extract all integers from strings in C++. We can put a string where numbers and no-numbers are present. We will extract all numeric values from it.

To solve this problem, we will use the stringstream class in C++. We will cut the string word by word and then try to convert it into integer type data. if the conversion is done, then it is integer and print the value.

Input: A string with some numbers “Hello 112 World 35 75”
Output: 112 35 75

Algorithm

Step 1:Take a number string
Step 2: Divide it into different words
Step 3: If a word can be converted into integer type data, then it is printed
Step 4: End

Example Code

 Live Demo

#include<iostream>
#include<sstream>
using namespace std;
void getNumberFromString(string s) {
   stringstream str_strm;
   str_strm << s; //convert the string s into stringstream
   string temp_str;
   int temp_int;
   while(!str_strm.eof()) {
      str_strm >> temp_str; //take words into temp_str one by one
      if(stringstream(temp_str) >> temp_int) { //try to convert string to int
         cout << temp_int << " ";
      }
      temp_str = ""; //clear temp string
   }
}
main() {
   string my_str = "Hello 112 World 35 75";
   getNumberFromString(my_str);
}

Output

112 35 75

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements