You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++实现字符串中数值及正偶数的统计?

解决C++提取任意字符串中的数值并统计正偶数的问题

Got it, let's work through how to modify your C++ code to handle any string with non-digit content, count total numbers, and count positive even numbers—just like the Python example you provided.

需求分析

Your original code only processes pure digit strings, but we need to:

  • Extract all integers (including negative ones) from a string with any non-digit characters
  • Count the total number of these integers
  • Count how many of those integers are positive and even

实现思路

Instead of just checking the start of the string, we'll traverse the entire input to find sequences of digits (including those prefixed with a - for negatives). For each valid number we extract, we'll update our counts accordingly.

完整C++代码

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

int main() {
    std::cout << "Enter a string: " << std::endl;
    std::string input;
    std::getline(std::cin, input);  // 读取整行输入,包含空格在内的所有内容

    int total_numbers = 0;
    int positive_evens = 0;
    const size_t input_len = input.size();
    size_t current_pos = 0;

    while (current_pos < input_len) {
        // 跳过非数字、非负号的字符
        while (current_pos < input_len && !std::isdigit(input[current_pos]) && input[current_pos] != '-') {
            current_pos++;
        }
        if (current_pos >= input_len) break;

        // 处理负号情况:确保负号后面跟着数字,否则跳过这个孤立的负号
        bool is_negative = false;
        if (input[current_pos] == '-') {
            is_negative = true;
            current_pos++;
            if (current_pos >= input_len || !std::isdigit(input[current_pos])) {
                continue;
            }
        }

        // 收集连续的数字字符,组成数字字符串
        std::string num_str;
        while (current_pos < input_len && std::isdigit(input[current_pos])) {
            num_str += input[current_pos];
            current_pos++;
        }

        // 将数字字符串转换为整数
        int num = std::stoi(num_str);
        if (is_negative) {
            num = -num;
        }

        // 更新统计计数
        total_numbers++;
        if (num > 0 && num % 2 == 0) {
            positive_evens++;
        }
    }

    std::cout << "数值总数:" << total_numbers << ",正偶数:" << positive_evens << std::endl;
    return 0;
}

代码说明

  • std::getline: 读取整行输入,避免了std::cin >> s只能读取到第一个空格的局限。
  • 字符遍历逻辑: 跳过无关字符,精准定位数字序列的起始位置。
  • 负号处理: 只把后面跟着数字的负号当作负数的一部分,避免误判孤立的负号。
  • 数字提取与转换: 收集连续数字字符后转为整数,确保数值的正确性。
  • 计数更新: 每提取到一个有效数字就更新总数,同时判断是否为正偶数并更新对应计数。

测试示例

  • 输入:29 coaches 28 → 输出:数值总数:2,正偶数:1
  • 输入:75,41,14,8,73,45,-16 → 输出:数值总数:7,正偶数:2(和你提供的Python示例结果一致,正偶数为14和8)

内容的提问来源于stack exchange,提问作者Shu Herm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:16:31