简体   繁体   中英

How to read space separated numbers from console?

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.

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::string s, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM