【问题标题】:C++ Converting a string of integers into an array of integers? [duplicate]C ++将整数字符串转换为整数数组? [复制]
【发布时间】:2013-02-06 22:00:56
【问题描述】:

我正在读取文件中的一行输入,例如“5 8 12 45 8 13 7”。

我可以将这些整数直接放入数组中,还是必须先将它们放入字符串中?

如果最初必须使用字符串,我如何将这个整数字符串转换为数组?

输入:“5 8 12 45 8 13 7” => 到数组中:{5,8,12,45,8,13,7}

【问题讨论】:

标签: c++ arrays string integer


【解决方案1】:

不,您不需要将它们转换为字符串。使用 C++ 标准库的容器和算法,这实际上非常简单(只要分隔符是空格或空格序列,它就可以工作):

#include <iterator>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;

    // An easy way to read a vector of integers from the standard input
    std::copy(
        std::istream_iterator<int>(std::cin), 
        std::istream_iterator<int>(), 
        std::back_inserter(v)
        );

    // An easy wait to print the vector to the standard output
    std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
}

【讨论】:

  • 如何打印这个数组?抱歉,我在努力学习这种语言。
  • @AaronPorter:我添加了一种将向量打印到标准输出的简单方法。如果对您有帮助,请考虑接受此答案。
  • @AndyProwl 他还可以考虑查看重复问题的列表,这些问题涵盖了这个特定的问题。
  • @SamiKenjat:哦,当然这是他本来可以做的另一件好事,但由于他没有这样做,而是他在问我更多问题,我很感激他在至少。只是让我觉得自己不像是一个帮助台。
猜你喜欢
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 2012-04-30
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多