C++ Program to take out integer from comma separated string


Suppose we have a string where we have few integers which are separated by comma. We shall have to separate them out and display each integer in different line. To do this we shall use stringstream (under sstream library) in C++. This is one string based stream class present in C++. We can use extraction operator (<<) to extract something, insertion operator (>>) to insert something and str() functions to set contents of underlying string device object.

So, if the input is like s = "56,9,85,256,47", then the output will be

56
9
85
256
47

To solve this, we will follow these steps −

  • Define an array take_int(string str)

    • create one stringstream object called ss

    • Define an array result

    • while new integer item taken from ss into temp is not null, do:

      • insert tmp at the end of result

      • skip comma character by taking out single character

    • return result

  • From the main method do the following:

  • Define an array integers = take_int(s)

  • for initialize i := 0, when i < size of integers, update (increase i by 1), do:

    • display integers[i]

Example

Let us see the following implementation to get better understanding −

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
vector<int> take_int(string str) {
    stringstream ss(str);
    vector<int> result;
    char ch;
    int tmp;
    while(ss >> tmp) {
        result.push_back(tmp);
        ss >> ch;
    }
    return result;
}
int main(){
    string s = "56,9,85,256,47";
    vector<int> integers = take_int(s);
    for(int i = 0; i < integers.size(); i++)
        cout << integers[i] << "\n";
}

Input

56,9,85,256,47

Output

56
9
85
256
47

Updated on: 07-Oct-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements