Search code examples
c++arrayshistogram

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


I'm having trouble with a piece of code. I'm trying to calculate a histogram inside a boolean function. I have this piece of code that I've written for another program, that I know works. The difference now is that it's inside a if and else if statement. The program takes a string from the user and stores that in an array. The array is looped through and is expected to calculate the number of letters, example the total number of H:s entered and also the total number of letters entered, example a total of 10 letters entered.

What I'm getting right now is, let's say I enter the text: "hello". I get a total number of 7 (always two more than I entered, but not if I enter a empty string). And it's always an extra "H" and "O". So for "hello", I get: e: 1 h: 2 l: 2 o: 2

I have absolutely no clue what's going on here, and I'm not really sure what to search for either. I'm quite new with 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;
}
}

I guess I'm having problem with the else if statement, since this piece of code is working in another program, where it's passed through an while loop.

EDIT!! To show how inText is created.

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

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

Solution

  • An edit has shown that the loops are reading past the end of the input string.

    The first loop after the !inText.empty() check should be

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

    Alternatively, you could just write the whole thing as:

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