如何拆分空格分隔的整数字符串并存储至整数vector中?
拆分空格分隔的整数字符串并存入vector的方法
嘿,这个问题在C++开发里挺常见的,我给你分享几种靠谱的实现方式,最推荐的是用标准库的std::stringstream,简单又省心:
方法一:使用std::stringstream(推荐)
这是处理这类场景最简洁的方案,只需要用到<sstream>和<vector>这两个标准头文件:
#include <iostream> #include <vector> #include <sstream> #include <string> int main() { std::string input = "116 119 220 250"; std::vector<int> nums; std::stringstream ss(input); int num; // 逐个读取整数,自动跳过所有空白字符(包括多个空格、制表符、换行) while (ss >> num) { nums.push_back(num); } // 可选:验证结果 for (int n : nums) { std::cout << n << " "; } return 0; }
为什么推荐这个?
std::stringstream会自动处理各种空白分隔符,不用你手动判断空格位置,容错性很强- 代码逻辑清晰,几乎不会出错,维护起来也方便
方法二:手动分割字符串(自定义场景)
如果你需要更精细的控制(比如同时处理空格和逗号这类混合分隔符),可以手动遍历字符串来分割:
#include <iostream> #include <vector> #include <string> int main() { std::string input = "116 119 220 250"; std::vector<int> nums; size_t start = 0; size_t end = input.find(' '); while (end != std::string::npos) { // 截取两个空格之间的子串,转成整数存入vector std::string num_str = input.substr(start, end - start); nums.push_back(std::stoi(num_str)); start = end + 1; end = input.find(' ', start); } // 处理最后一个没有后续空格的整数 nums.push_back(std::stoi(input.substr(start))); // 可选:验证结果 for (int n : nums) { std::cout << n << " "; } return 0; }
注意:
- 这个方法需要自己处理字符串的索引,适合对分割逻辑有特殊需求的场景,但代码相对繁琐一些
额外提示
如果输入字符串里可能存在非数字字符,记得加上异常捕获(比如try-catch包裹std::stoi或者检查stringstream的状态),避免程序崩溃。
内容的提问来源于stack exchange,提问作者Muhammad Iqbal
相关产品推荐
相关产品推荐

