Barney Chambers
Barney Chambers

Reputation: 2783

sstream not populating vector C++

With input in the command line:

1 2 3

Which is stored in 'line' my vector is only being populated with

1

What am I doing wrong? Here is the code

string line;
    string buffer;
    int a,b,base;

    cin >> line;
    stringstream ss(line);
    std::vector<string> tokens;
    while( ss >> buffer){
        tokens.push_back(buffer);
    }
    for(int i=0; i<tokens.size(); i++){cout << tokens[i] << endl;}

Upvotes: 0

Views: 67

Answers (1)

PC Luddite
PC Luddite

Reputation: 6108

Your problem is here:

cin >> line;

Note that this function

operator>>(istream& is, string& str)

gets all characters until the first occurrence of whitespace (in the case of input 1 2 3, it stops on the space after 1)

Try using the function getline(), which reads the string up until the first occurrence of a newline.

This seems to work:

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

using namespace std;

int main(void) {
    string line;
    string buffer;
    int a,b,base;

    getline(cin, line);
    stringstream ss(line);
    vector<string> tokens;
    while( ss >> buffer){
        tokens.push_back(buffer);
    }
    for(int i=0; i<tokens.size(); i++){cout << tokens[i] << endl;}

    return 0;
}

Upvotes: 4

Related Questions