我正在读取来自诸如“5 8 12 45 8 13 7”等文件的输入行。C++将整数字符串转换为整数数组?
我可以将这些整数直接放入数组中,还是必须先将它们放入一个字符串?
如果最初使用一个字符串是强制性的,我该如何将这个整数字符串转换为一个数组?
输入: “5 8 12 45 8 13 7”=>到一个数组为这样:{5,8,12,45,8,13,7}
我正在读取来自诸如“5 8 12 45 8 13 7”等文件的输入行。C++将整数字符串转换为整数数组?
我可以将这些整数直接放入数组中,还是必须先将它们放入一个字符串?
如果最初使用一个字符串是强制性的,我该如何将这个整数字符串转换为一个数组?
输入: “5 8 12 45 8 13 7”=>到一个数组为这样:{5,8,12,45,8,13,7}
否,则不需要将它们转换为一个字符串。与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他也可以考虑查看覆盖这个特殊问题的重复问题清单。 –
你怎么读线路?请张贴该代码:它是相关的。 –
我相信这个问题是以下内容的副本: http://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-int-integers http://stackoverflow.com/questions/ 1894886/parsing-a-comma-delimited-stdstring http://stackoverflow.com/questions/4170440/regex-how-to-find-the-maximum-integer-value-of-a-pattern http:// stackoverflow.com/questions/2619227/best-way-to-get-ints-from-a-string-with-whitespace http://stackoverflow.com/questions/1141741/int-tokenizer –