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

C++字符串数字求和及货币类分输入00-99范围验证问询

我来帮你解决这两个C++开发中的问题:

问题1:如何在C++中计算字符串内数字的总和?

要计算字符串里所有数字字符的总和,核心思路就是遍历字符串的每个字符,判断是否是数字,若是就转换成对应的整数累加。这里可以用C标准库的isdigit()函数来判断字符类型,数字字符转整数只需减去'0'(因为ASCII码中'0'到'9'是连续的)。

给你一个完整的示例代码:

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

// 计算字符串中数字字符的总和
int sumDigits(const std::string& inputStr) {
    int total = 0;
    for (char c : inputStr) {
        // 仅处理数字字符
        if (std::isdigit(c)) {
            total += c - '0'; // 字符转对应整数,比如'3' - '0' = 3
        }
    }
    return total;
}

int main() {
    std::string test = "Hello123World45!";
    std::cout << "字符串中数字总和:" << sumDigits(test) << std::endl; // 输出1+2+3+4+5=15
    return 0;
}

如果你的字符串里可能包含负数符号(比如"-123"),但问题没提到这种场景,所以上面的代码只处理0-9的数字字符,符合常规需求。

问题2:验证货币分的输入是否在00-99范围内

针对你的Money类场景,要验证分的输入合法,需要满足三个核心条件:输入全是数字、数值在0-99之间、避免超长输入导致溢出。我给你写一个实用的验证函数,再结合你的deposit方法补充完整:

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

class Money {
private:
    long int totalCents; // 用分存储总金额,避免浮点误差
public:
    Money() : totalCents(0) {}

    bool isValidCents(const std::string& centsStr) {
        // 1. 空输入直接非法
        if (centsStr.empty()) {
            return false;
        }
        // 2. 检查所有字符是否都是数字
        for (char c : centsStr) {
            if (!std::isdigit(c)) {
                return false;
            }
        }
        // 3. 长度超过2的直接非法(因为最大是99,两位数字)
        if (centsStr.length() > 2) {
            return false;
        }
        // 4. 转换为整数后判断范围
        int cents = std::stoi(centsStr);
        return cents >= 0 && cents <= 99;
    }

    void deposit() {
        std::string eurosStr, centsStr;
        std::cout << "How much do you want to deposit? (Euros: ";
        std::cin >> eurosStr;
        std::cout << "Cents: ";
        std::cin >> centsStr;

        // 验证分的输入
        if (!isValidCents(centsStr)) {
            std::cerr << "Invalid cents input! Please enter a value between 00 and 99." << std::endl;
            return;
        }

        // 转换为总分数值
        int euros = std::stoi(eurosStr);
        int cents = std::stoi(centsStr);
        totalCents += euros * 100L + cents;

        // 输出反馈
        std::cout << "Deposit successful! Current balance: " 
                  << totalCents / 100 << "." 
                  << (totalCents % 100 < 10 ? "0" : "") << totalCents % 100 
                  << " EUR" << std::endl;
    }
};

// 测试示例
int main() {
    Money myWallet;
    myWallet.deposit();
    return 0;
}

关键细节说明:

  • 先检查输入是否为空或包含非数字字符,快速过滤非法输入;
  • 提前判断字符串长度是否超过2,避免stoi转换超长字符串时溢出;
  • 转换为整数后再判断0-99的范围,兼容用户输入1位数字(比如"5"对应05分)的合法场景;
  • 最终用long int存储总分数值,完全避免浮点类型的精度问题,这也是货币类的最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:31:55