How to read a single line of numbers into different variables? [closed]

左心房为你撑大大i 提交于 2019-12-02 14:51:37

From your output message, it seems like you're expecting at least 6 integers as input. That means you want a container that you can add an arbitrary number of elements to, like std::vector<int> Nums;. You can then use std::copy to extract ints from cin and push them into the vector with a std::back_inserter:

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

See it in action.

There may be a reasonable number of things here that you're not familiar with:

  1. std::copy is an algorithm that copies from one range to another range. The first two arguments denote the beginning and end of the range to copy from, and the third argument denotes the beginning of the range to copy to.
  2. std::istream_iterator is an iterator type that extracts from the stream you give it when it is incremented.
  3. std::istream_iterator<int>(std::cin) constructs an iterator that will extract ints from std::cin
  4. std::istream_iterator<int>() constructs a special end-of-stream iterator. It represents the end of any arbitrary stream. This means that the copy algorithm will stop when it reaches the end of the stream.
  5. std::back_inserter creates another iterator that calls push_back on the container you give it every time it is assigned to. As the copy algorithm will assign to this iterator the ints extracted from the stream, it will push them all into the vector Nums.

If that's too complicated, here's another version that uses less library components:

int val;
while (std::cin >> val) {
  Nums.push_back(val);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!