views:

331

answers:

6

How would I get a list of numbers from the user and then tokenize them.

This is what I have but it doesn't get anything except for the first number:

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

using namespace std;

int main()
{

    string line = "";
    cin >> line;

    stringstream lineStream(line);

    int i;
    vector<int> values;

    while (lineStream >> i)
        values.push_back(i);

    for(int i=0; i<values.size(); i++)
        cout << values[i] << endl;

    system("PAUSE");
    return 0;
}

Related Posts:
C++, Going from string to stringstream to vector
Int Tokenizer

+3  A: 

I believe cin >> breaks on whitespace, which means you're only getting the first number entered.

try:

getline(cin, line);
Donnie DeBoer
not if you put it in a loop: while(std::cin >> i) { /* Do STUFF */ }
Martin York
why loop, when you can do it in one call?
Donnie DeBoer
A: 

Like Donnie mentioned cin breaks on whitespace, so do overcome this we can use a 'getline()', the following example works nicely:

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

using namespace std;

int main()
{

    string line = "";
    ::getline(std::cin,line,'\n');

    std::stringstream lineStream(line);

    int i;
    std::vector<int> values;

    while (lineStream >> i)
        values.push_back(i);

    for(int i=0; i<values.size(); i++)
        cout << values[i] << endl;

    system("PAUSE");
    return 0;
}
DeusAduro
A: 

on top of main

string line = "";
getline (cin, line );
stringstream lineStream(line);
Junier
+5  A: 

Here is probably the easiest way to read values from cin into a container:

#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    std::vector<int> values;
    std::copy(
        std::istream_iterator<int>(std::cin), 
        std::istream_iterator<int>(),
        std::back_inserter(values));

    // For symmetry with the question copy back to std::cout
    std::copy(
        values.begin(),
        values.end(),
        std::ostream_iterator<int>(std::cout,"\n"));

}
Pavel Minaev
A: 

Yep, and is the string version of getline, no the istream one.

Hai
A: 

OK: Pavel Minaev has the best answer.
But all the people mentioning that cin breaks on white space.
That is a good thing (because it also ignores white space);

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

using namespace std;

int main()
{

    int i;
    vector<int> values;

    // prefer to use std::copy() but this works.
    while (std::cin >> i)
    {
        values.push_back(i);
    }

    // prefer to use std::copy but this works.
    for(vector<int>::const_iterator loop = values.begin();loop != values.end();++loop)
    {
        cout << *loop << endl;
    }

    return 0;
}
Martin York