当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - get list of numbers from stdin and tokenize them

问题描述:

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

网友答案:

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

try:

getline(cin, line);
网友答案:

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

}
网友答案:

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;
}
网友答案:

on top of main

string line = "";
getline (cin, line );
stringstream lineStream(line);
网友答案:

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

网友答案:

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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: