Extract all integers from string in C++

C++Server Side ProgrammingProgramming

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


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

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";


112 35 75
Published on 28-Mar-2019 13:12:18