如何读取单行数字到不同的变量? [英] How to read a single line of numbers into different variables?

查看:102
本文介绍了如何读取单行数字到不同的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计划如下:

#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 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 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 是从一个范围复制到另一个范围的算法。前两个参数表示要复制范围的开始和结束,第三个参数表示要复制到的范围的开头。

  2. std :: istream_iterator 是一种迭代器类型,它从您在增加流时提供的流中提取。

  3. std :: istream_iterator< int> std :: cin)构造一个迭代器,将从 std :: cin int >

  4. std :: istream_iterator< int>()构建特殊的 。它表示任意任意流的结束。这意味着 copy 算法在到达流末尾时会停止。

  5. std :: back_inserter 创建另一个迭代器,它在每次分配给它的容器上调用 push_back 。由于 copy 算法会将从流中提取的 int 分配给此迭代器,因此会将它们全部推入

  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);
}

这篇关于如何读取单行数字到不同的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆