开发者

How to read space separated numbers from console?

开发者 https://www.devze.com 2023-02-20 18:44 出处:网络
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.

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 i开发者_如何学Pythonstream_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.


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


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.


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;
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号