Search code examples
c++linked-listtokenizeistringstream

Parse a string to int


I'm pretty new to coding, and I was hoping someone could help me out? I'm trying to read in a line of space delimited integers and parse them into (ultimately into a linked list) a vector.

so once i have a vector of ints, there are iterators for STL vector, but how can i iterate through the nodes in a link list not in STL?

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main(int argc, char** argv) {    
    cout << "Enter some integers, space delimited:\n";
    string someString;
    getline(cin, someString);

    istringstream stringStream( someString );
    vector<string> parsedString;
    char splitToken = ' ';

    //read throguh the stream
    while(!stringstream.eof()){
        string subString;
        getline( stringStream, subString, splitToken);
        if(subString != ""){
        parsedString.push_back(subString);
        }
   }

    return EXIT_SUCCESS;
}

Solution

  • stringstream can automatically handle delimiters like this:

    cout << "Enter some integers, space delimited:\n";
    string someString;
    getline(cin, someString);
    
    istringstream stringStream( someString );
    vector<int> integers;
    int n;
    while (stringStream >> n)
        integers.push_back(n);