在 C++ 中将字符串转换为整数数组

您所在的位置:网站首页 go字符串数组转int数组 在 C++ 中将字符串转换为整数数组

在 C++ 中将字符串转换为整数数组

2024-04-15 02:23| 来源: 网络整理| 查看: 265

使用 std::getline 和 std::stoi 函数在 C++ 中将 string 转换为 int 数组 在 C++ 中使用 std::string::find 和 std::stoi 函数将 string 转换为 int 数组 使用 std::copy 和 std::remove_if 函数在 C++ 中将 string 转换为 int 数组

本文将演示有关如何在 C++ 中将字符串转换为整数数组的多种方法。

使用 std::getline 和 std::stoi 函数在 C++ 中将 string 转换为 int 数组

std::stoi 用于将字符串值转换为带符号的整数,它采用一个类型为 std::string 的强制性参数。可选地,该函数可以接受 2 个附加参数,其中第一个可用于存储最后一个未转换字符的索引。第三个参数可以选择指定输入的数字基数。注意,我们假设用逗号分隔的数字作为输入字符串,例如 .csv 文件。因此,我们使用 getline 函数来解析每个数字,然后将该值传递给 stoi。通过在每次迭代中调用 push_back 方法,我们还将每个数字存储在 std::vector 容器中。

#include #include #include #include using std::cerr; using std::cout; using std::endl; using std::stoi; using std::string; using std::stringstream; using std::vector; int main(int argc, char *argv[]) { string text = "125, 44, 24, 5543, 111"; vector numbers; int num; stringstream text_stream(text); string item; while (std::getline(text_stream, item, ',')) { numbers.push_back(stoi(item)); } for (auto &n : numbers) { cout 使用 std::copy 和 std::remove_if 函数在 C++ 中将 string 转换为 int 数组

提取整数的另一种方法是将 std::copy 算法与 std::istream_iterator 和 std::back_inserter 结合使用。此解决方案将字符串值存储到向量中,并将其输出到 cout 流,但是可以轻松添加 std::stoi 函数以将每个元素转换为 int 值。请注意,以下示例代码仅将数字存储为字符串值。

#include #include #include #include using std::cerr; using std::cout; using std::endl; using std::stoi; using std::string; using std::stringstream; using std::vector; int main(int argc, char *argv[]) { string text = "125, 44, 24, 5543, 111"; vector nums; std::istringstream iss(text); copy(std::istream_iterator(iss), std::istream_iterator(), std::back_inserter(nums)); for (auto &n : nums) { n.erase(std::remove_if(n.begin(), n.end(), ispunct), n.end()); cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3