How to read space separated numbers from console?

后端 未结 5 1752
无人共我
无人共我 2021-01-12 03:13

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

相关标签:
5条回答
  • 2021-01-12 03:20

    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.

    0 讨论(0)
  • 2021-01-12 03:21

    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 讨论(0)
  • 2021-01-12 03:39

    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.

    0 讨论(0)
  • 2021-01-12 03:40

    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;
    }
    
    0 讨论(0)
  • 2021-01-12 03:44

    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);
    }
    
    0 讨论(0)
提交回复
热议问题