Question

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;
}
Was it helpful?

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);

OTHER TIPS

Since it's space delimiter, why not just:

#include <iostream>
using namespace std;

int main() {
    int a;
    vector<int> v;
    while (cin >> a) {
        v.push_back(a);
    }

    for (int i = 0; i < v.size(); ++i) {
        int b = v[i];
    }

    return 0;
}

And BTW, ctrl-D or a non-integer input, like char, will terminate this while.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top