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

C++中char数组字符计数器返回值错误问题咨询

你的C++字符统计程序错误分析与修正

核心错误点

  • 类名不匹配:main函数里写的Logic input;,但你定义的类是Counter,这会直接导致编译失败,改成Counter input;即可。
  • 字符串赋值逻辑完全错误:
    • setWord函数参数是单个char,根本无法接收整个字符串,需要改成const char* inputWord。
    • 函数内部this->word[20] = word;是越界操作(数组下标从0开始,char word[20]的有效下标范围是0-19),而且没有完成字符串复制,应该用strncpy做安全复制,还要手动添加字符串结束符:strncpy(this->word, inputWord, sizeof(this->word)-1); this->word[sizeof(this->word)-1] = '\0';。
    • 调用setWord时传text[20]是越界访问(char text[20]的最大下标是19),直接传text就行。
  • 冗余判断:charCount里的循环已经以word[i] != '\0'作为终止条件,内部再套一层相同判断完全没必要,直接计数即可。

修正后的完整代码

#include<iostream>
using namespace std;
#include<cstring>
#include <stdlib.h>

class Counter
{
public:
    char word[20];
    int totChar{ 0 };

    void setWord(const char* inputWord)
    {
        // 安全复制字符串,避免越界,手动添加结束符
        strncpy(this->word, inputWord, sizeof(this->word)-1);
        this->word[sizeof(this->word)-1] = '\0';
    }
    void setCount(int totChar)
    {
        this->totChar = totChar;
    }
    int getLength()
    {
        return totChar;
    }
    void charCount()
    {
        int n = 0;
        for (int i = 0; word[i] != '\0'; i++) {
            n++;
        }
        setCount(n);
    }
};


int main()
{
    char text[20];
    cout << "Enter the string:" << endl;
    cin >> text;
    Counter input;
    input.setWord(text);
    input.charCount();
    cout << input.getLength();
}

更简洁的C++风格实现(推荐)

直接用std::string替代字符数组,避免手动处理越界和结束符的问题:

#include<iostream>
#include<string>
using namespace std;

class Counter
{
public:
    string word;
    int totChar{ 0 };

    void setWord(const string& inputWord)
    {
        this->word = inputWord;
    }
    void setCount(int totChar)
    {
        this->totChar = totChar;
    }
    int getLength()
    {
        return totChar;
    }
    void charCount()
    {
        setCount(word.size());
    }
};


int main()
{
    string text;
    cout << "Enter the string:" << endl;
    cin >> text;
    Counter input;
    input.setWord(text);
    input.charCount();
    cout << input.getLength();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:42:50