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

C++统计用户输入字符串大小写字母、数字数量返回0问题求助

问题排查与修正

代码存在的4处核心错误:

  • 字符串内容未拷贝到数组:main函数中读取输入到std::string s后,没有将s的内容复制到声明的char text[]数组中,数组内全是未初始化的垃圾值,统计自然全部为0。
  • 字符串长度获取错误:sizeof(s)获取的是std::string对象本身的内存大小(通常是固定值如24/32字节,和字符串内容长度无关),应该调用s.size()获取字符串实际字符数。
  • 循环条件逻辑错误:processData中的循环条件i <= text[size]完全错误,text[size]属于数组越界访问的非法值,正确循环条件应为i < size。
  • 小写字母判断函数调用错误:统计小写字母的分支错误调用了isUpperCase,永远不会触发小写计数逻辑,应改为调用isLowerCase。

修正后的完整代码:

import<string>
import<iostream>

bool isNumber(char ch) {
    return ch >= '0' && ch <= '9';
}

bool isUpperCase(char ch) {
    return ch >= 'A' && ch <= 'Z';
}

bool isLowerCase(char ch) {
    return ch >= 'a' && ch <= 'z';
}

void processData(const char text[], int size) {
    int upperCase = 0;
    int lowerCase = 0;
    int numbers = 0;
    for (int i = 0; i < size; i++) {
        if (isNumber(text[i])) {
            numbers++;
        } else if (isUpperCase(text[i])) {
            upperCase++;
        } else if (isLowerCase(text[i])) {
            lowerCase++;
        }
    }
    std::cout << "There are " << upperCase << " uppercase letters in this string." << std::endl;
    std::cout << "There are " << lowerCase << " lowercase letters in this string." << std::endl;
    std::cout << "There are " << numbers << " numbers in this string." << std::endl;
}

int main()
{
    std::cout << "Enter some text: ";
    std::string s;
    std::getline(std::cin, s);
    // 直接用string的内部字符数组,无需额外拷贝
    processData(s.data(), s.size());
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:54:04