从string中提取num存入vector(C++)

📌 C++ 实现:从字符串中提取数字并存入 vector<int>

✅ 功能说明:

该程序接受任意字符串输入,从中提取出连续的数字子串,将它们转换为整数并存入一个 vector<int> 容器中。


🧠 知识点涉及:

  • std::getline():接收整行字符串输入
  • std::isdigit():判断字符是否为数字
  • std::stoi():将字符串转换为整数
  • std::vector<int>:动态数组容器
  • 字符串处理逻辑

💡 完整代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <cctype>

using namespace std;

int main() {
    string input;
    cout << "请输入字符串:";
    getline(cin, input);  // 接收整行字符串,支持空格

    vector<int> numbers;   // 用于保存提取出的数字
    string current;        // 临时存储当前构建的数字字符串

    // 遍历输入字符串的每个字符
    for (char ch : input) {
        if (isdigit(ch)) {
            current += ch;  // 如果是数字,加入当前数字串
        } else if (!current.empty()) {
            // 遇到非数字,且当前数字串非空时,转换并存入 vector
            numbers.push_back(stoi(current));
            current.clear();  // 清空临时数字串,准备下一个
        }
    }

    // 处理字符串结尾是数字的情况
    if (!current.empty()) {
        numbers.push_back(stoi(current));
    }

    // 输出提取出的数字
    cout << "提取出的数字为:" << endl;
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}
posted @ 2025-04-24 14:37  vv大人  阅读(106)  评论(0)    收藏  举报