How to read space separated numbers from console?

房东的猫 提交于 2019-12-01 00:43:39

问题


I'm trying to do a simple task of reading space separated numbers from console into a vector<int>, but I'm not getting how to do this properly.

This is what I have done till now:

int n = 0;
vector<int> steps;
while(cin>>n)
{
    steps.push_back(n);
}

However, this requires the user to press an invalid character (such as a) to break the while loop. I don't want it.

As soon as user enters numbers like 0 2 3 4 5 and presses Enter I want the loop to be broken. I tried using istream_iterator and cin.getline also, but I couldn't get it working.

I don't know how many elements user will enter, hence I'm using vector.

Please suggest the correct way to do this.


回答1:


Use a getline combined with an istringstream to extract the numbers.

std::string input;
getline(cin, input);
std::istringstream iss(input);
int temp;
while(iss >> temp)
{
   yourvector.push_back(temp);
}



回答2:


To elaborate on jonsca's answer, here is one possibility, assuming that the user faithfully enters valid integers:

string input;
getline(cin, input);

istringstream parser(input);
vector<int> numbers;

numbers.insert(numbers.begin(),
               istream_iterator<int>(parser), istream_iterator<int>());

This will correctly read and parse a valid line of integers from cin. Note that this is using the free function getline, which works with std::strings, and not istream::getline, which works with C-style strings.




回答3:


This code should help you out, it reads a line to a string and then iterates over it getting out all numbers.

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

int main() {
    std::string line;
    std::getline(std::cin, line);
    std::istringstream in(line, std::istringstream::in);
    int n;
    vector<int> v;
    while (in >> n) {
        v.push_back(n);
    }
    return 0;
}



回答4:


Also, might be helpful to know that you can stimulate an EOF - Press 'ctrl-z' (windows only, unix-like systems use ctrl-d) in the command line, after you have finished with your inputs. Should help you when you're testing little programs like this - without having to type in an invalid character.




回答5:


Prompt user after each number or take number count in advance and loop accordingly. Not a great idea but i saw this in many applications.



来源:https://stackoverflow.com/questions/5497277/how-to-read-space-separated-numbers-from-console

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!