Reading a list of integer in a single input line in C++

[亡魂溺海] 提交于 2019-12-18 07:03:17

问题


I'm trying to read multiple integers from a single input line into an array eg. Input: 100 200 300 400, so the array is: a[0] = 100, a[1] = 200, a[2] = 300, a[3] = 400 The thing is, the number of integers are unknown, so the size of the array is unknown.


回答1:


You should use a container that automatically resizes itself, such as std::vector.

For example, something like this:

#include <string>
#include <iostream>
#include <sstream>
#include <utility>
#include <iterator>

std::string line;
getline(instream, line);
std::istringstream this_line(line);
std::istream_iterator<int> begin(this_line), end;
std::vector<int> values(begin, end);



回答2:


You could use std::vector for this:

std::vector<int> myVector;

std::string line;
std::getline(std::cin, line);
std::istringstream os(line);

int i;
while(os >> i)
    myVector.push_back(i);

This code requires following includes: <iostream>, <string>, <sstream> and <vector>.




回答3:


Inserters and stream iterators can do this nicely:

#include <iterator>
#include <vector>
#include <iostream>
#include <algorithm>

std::vector<int> numbers;

std::copy(std::istream_iterator<int>(std::cin),
          std::istream_iterator<int>(),
          std::back_inserter(numbers));

Or, as @Ben Voigt has it, construct the vector from the input in one go (if that's an option):

std::vector numbers(std::istream_iterator<int>(std::cin),
                    std::istream_iterator<int>());

You can replace std::cin by a suitable string stream if your input requirements are more complex.



来源:https://stackoverflow.com/questions/9354192/reading-a-list-of-integer-in-a-single-input-line-in-c

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