如何读取单行数字到不同的变量? [英] How to read a single line of numbers into different variables?
问题描述
计划如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Code
int num1, num2, num3, num4, num5, num6;
int num[6] = { num1, num2, num3, num4, num5, num6 };
cout << "Enter one line containing at least 6 integers." << endl;
getline(cin, num);
输入行数:1 2 87 1 2 123 44
Line of input: 1 2 87 1 2 123 44
我需要将每个数字存储到变量Num1,Num2,Num3等。
And I need to store each number into variables Num1, Num2, Num3, etc.
推荐答案
消息,似乎您希望至少 6个整数作为输入。这意味着你想要一个容器,你可以添加任意数量的元素,如 std :: vector< int> Nums;
。然后,您可以使用 std :: copy
从 cin $ c中提取
int
$ c>并将它们推入带有 std :: back_inserter
的向量中:
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 int
s 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:
-
std :: copy
是从一个范围复制到另一个范围的算法。前两个参数表示要复制范围的开始和结束,第三个参数表示要复制到的范围的开头。 -
std :: istream_iterator
是一种迭代器类型,它从您在增加流时提供的流中提取。 -
std :: istream_iterator< int> std :: cin)
构造一个迭代器,将从std :: cin
int > -
std :: istream_iterator< int>()
构建特殊的 。它表示任意任意流的结束。这意味着copy
算法在到达流末尾时会停止。 -
std :: back_inserter
创建另一个迭代器,它在每次分配给它的容器上调用push_back
。由于copy
算法会将从流中提取的int
分配给此迭代器,因此会将它们全部推入
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.std::istream_iterator
is an iterator type that extracts from the stream you give it when it is incremented.std::istream_iterator<int>(std::cin)
constructs an iterator that will extractint
s fromstd::cin
std::istream_iterator<int>()
constructs a special end-of-stream iterator. It represents the end of any arbitrary stream. This means that thecopy
algorithm will stop when it reaches the end of the stream.std::back_inserter
creates another iterator that callspush_back
on the container you give it every time it is assigned to. As thecopy
algorithm will assign to this iterator theint
s extracted from the stream, it will push them all into the vectorNums
.
如果这太复杂了,库组件:
If that's too complicated, here's another version that uses less library components:
int val;
while (std::cin >> val) {
Nums.push_back(val);
}
这篇关于如何读取单行数字到不同的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!