Monday, 25 July 2016

C++ Extract multiple int from one string using stringstream

Sometimes you might get the input such as "23,4,56" and you would like to extract them as integers. There needed some kind of iteration through the string. However, we do not know the length of how many numbers are there in the string.

I write the following case for this function.

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main()
{
    vector<int> vec;
    string input = "23,4,56";
    stringstream ss;
    ss << input;
    string temp;
    int iTemp;

    while(std::getline(ss, temp,',')) {
        if(std::stringstream(temp)>>iTemp)
        {
            vec.push_back(iTemp);
        }
    }
    
    for(int i=0;i<vec.size();i++)
    {
        cout<<vec[i]<<endl;
    }
    
    return 0;
}

ref:
http://stackoverflow.com/questions/21594533/c-extract-int-from-string-using-stringstream

No comments:

Post a Comment