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


© 2019-2026 Algotree.org | All rights reserved.

This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit algotree.org

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand. - Martin Fowler"