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

标签 c++ c

什么是转换字符串的简单方法

“1 0 2 1 4 5 6 195”

到 int 数组(或 vector )?我知道可能的解决方案,但它们对于我的目的来说似乎都太复杂了(字符串的格式如示例中所示)。 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 ) );

关于c++ - 将字符串转换为 int 数组的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22366593/

相关文章:

c++ - protobuf 可以部分读取吗?

c++ - 将 unsigned char *buf=NULL 翻译成 Pascal?

c++ - 在 C++ 类中使用 OpenMP

无法让 'child' 和 'parent' 正常通信

c - 如何触发内存范围访问异常?

c - pthread_cond_timedwait 在 FreeBSD 中返回 EPERM

c++ - 在 EXE 中循环无限运行的奇怪问题

c++ - 使用 WndClass 访问违规读取位置

c - 打字过程中如何防止数据丢失?

c - 以 IEEE 754 交换格式记录/读取 C double