Program looks like:
#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);
Line of input: 1 2 87 1 2 123 44
And I need to store each number into variables Num1, Num2, Num3, etc.
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));
There may be a reasonable number of things here that you're not familiar with:
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);
}
来源:https://stackoverflow.com/questions/21614999/how-to-read-a-single-line-of-numbers-into-different-variables