繁体   English   中英

如何在整数数组中拆分输入字符串(C ++)

[英]How to split an input string in an integer array(c++)

我才刚刚开始学习c ++。 在Java中,要分割输入,您只需要使用split方法从输入分割空格即可。 还有没有其他简单的方法可以将字符串输入拆分为整数数组? 我不在乎效率; 我只想要一些可以帮助我理解如何从输入中分割空格的代码。

一个例子是:输入:1 2 3 4代码:

int list[4];
list[0]=1;
list[1]=2;
list[2]=3;
list[3]=4;

在C ++中,基本上也可以通过单个函数调用来处理。

例如这样:

std::string input = "1 2 3 4";  // The string we should "split"

std::vector<int> output;  // Vector to contain the results of the "split"

std::istringstream istr(input);  // Temporary string stream to "read" from

std::copy(std::istream_iterator<int>(istr),
          std::istream_iterator<int>(),
          std::back_inserter(output));

参考文献:


如果输入尚未在字符串中,而是要直接从标准输入std::cin读取,则它甚至更简单(因为您不需要临时字符串流):

std::vector<int> output;  // Vector to contain the results of the "split"

std::copy(std::istream_iterator<int>(std::cin),
          std::istream_iterator<int>(),
          std::back_inserter(output));
#include <iostream>
#include <array>

int main()
{
  int list[4];
  for (int i=0; i<4; ++i)
  {
     std::cin >> list[i];
  }

  std::cout << "list: " << list[0] << ", " << list[1] << ", " << list[2] << ", " << list[3] << "\n";

  return 0;
}

这将在空白处分割输入,并假设输入中至少有4个整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM