C++

C++ : Parsing a string of integers into an integer array / vector

A string of integers could easily be parsed and stored into an array / vector of int using an object of stringstream.
We could create an object of stringstream using the given string of integers, and then extract the integers using » operator.

#include<iostream>
#include<sstream>
#include<vector>

using namespace std;

int main() {

    int num;
    vector<int> vec;
 
    cout << "Enter string containing integers : ";
    string str;
    getline(cin, str);
    stringstream ss(str);

    while ( ss >> num ) { 
        vec.push_back(num);
    }   

    cout << "Vector obtained from string of integers : ";
    for (auto n : vec) {
        cout << n << " ";
    }   
    return 0;
}

Output

Enter string containing integers : 5 3 4 7 6 9
Vector obtained from string of integers : 5 3 4 7 6 9


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.