简体   繁体   English

将字符串转换为int数组的最简单方法

[英]Easiest way to convert string to int array

What is an easy way to convert a string 转换字符串的简便方法是什么

"1 0 2 1 4 5 6 195" “ 1 0 2 1 4 5 6 195”

to an int array (or a vector)? 到一个int数组(或一个向量)? I am aware of the possible solutions but they all seem too complicated for my purposes (string is formatted as given in example). 我知道可能的解决方案,但它们对我而言似乎都太复杂了(字符串的格式如示例所示)。 std::string or char[] are both ok. std :: string或char []都可以。

#include <string>
#include <vector>
#include <sstream>
#include <iterator>

// get string
std::string input = "1 0 2 1 4 5 6 195";

// convert to a stream
std::stringstream in( input);

// convert to vector of ints
std::vector<int> ints;
std::copy( std::istream_iterator<int, char>(in),
                std::istream_iterator<int, char>(), std::back_inserter( ints ) );

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

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