为什么我的数组包含我没有输入的字母?

Why does my array contain letters that I have not entered?

我在处理一段代码时遇到了问题。我正在尝试计算布尔函数内的直方图。我有这段代码是我为另一个程序编写的,我知道它可以工作。现在的区别在于它在 if 和 else if 语句中。该程序从用户那里获取一个字符串并将其存储在一个数组中。该数组被循环遍历,预计会计算字母的数量,例如输入的 H:s 的总数以及输入的字母总数,例如总共输入 10 个字母。

我现在得到的是,假设我输入了文本:“你好”。我得到的总数是 7(总是比我输入的多两个,但如果我输入一个空字符串则不会)。它总是一个额外的“H”和“O”。所以对于“你好”,我得到: 电子:1 小时:2 我:2 o: 2

我完全不知道这里发生了什么,我也不确定要搜索什么。我对 C++ 很陌生。

bool Text::beraknaHistogramAbs(){
int i = 0;
int j = 0;

if (inText.empty()){
    cout << "Tom textrad!" << endl;
    exit (EXIT_FAILURE);

}

else if(!inText.empty()) {
    for (i = 0; i < ANTAL_BOKSTAVER; i++){ //ANTAL_BOKSTAVER is 26.
        if (inText[i] >= 'a' && inText[i] <= 'z'){ //inText is the string from the user.
            j = inText[i] - 'a';
            ++absolutHisto[j]; //Is initialized to zero in the default constructor.
    }
        if (inText[i] >= 'A' && inText[i] <= 'Z'){
            j = inText[i] - 'A';
            ++absolutHisto[j];
    }
}
for (i = 0; i < ANTAL_BOKSTAVER; i++){
    antal += absolutHisto[i]; //antal is an integer for the total number of letters.
}
return true;
}
}

我想我的 else if 语句有问题,因为这段代码在另一个程序中运行,它通过 while 循环传递。

编辑!!展示 inText 是如何创建的。

void Text::setText(const string &nyText){

cout <<"Ge en rad med text:" << endl;
getline(cin,inText);

编辑显示循环正在读取输入字符串的末尾。

!inText.empty()检查后的第一个循环应该是

for (i = 0; i < inText.length(); i++)

或者,您可以将整个内容写成:

for (const char x : inText) {
    if (x >= 'A' && x <= 'Z') { absolutHisto[x-'A']++; }
    if (x >= 'a' && x <= 'z') { absolutHisto[x-'a']++; }
}