0

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;}
Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

1 Answers1

4

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;
}
PC Luddite
  • 5,883
  • 6
  • 23
  • 39