简体   繁体   中英

C++ counter not working

The file I read had the string "hello" that was all. There were no errors and the program said "You have 135197296 E's" which is obviously wrong. I'm stumped here. I'm new to C++ and it looked this would be a fun and easy program to do... I was wrong.

I don't know if it matters but the completed program should be able to open a file the user provides, read the file, and put the frequencies of letters onto a separate file. Obviously, I haven't gotten there yet and I'm only asking for help on this bit :)

 int main() {
    string filenamein, filenameout;
    char character;
    ifstream fileC;
    int tletter, eletter;

    cout << "which file do you want to open?";
    cin >> filenamein;

    fileC.open(filenamein.c_str());
    if (fileC)
    {
        while (fileC)
        {
            fileC.get(character);
            char e, E;
            if (character == 'e'|| character == 'E')
            {
                eletter++;
            }
        }
    }

    cout<< "You have " << eletter <<" E's";
    fileC.close();

    return 0;
}

In C++, primitive variables such as int are not initialized unless you explicitly initialize them. This would generally be inefficient because sometimes you don't know the first value you want a variable to assume when you declare it, and so initializing it to, eg, 0 would be a redundant write operation.

Thus, if you want your eletter to start at 0 , you have to do something like this.

int eletter = 0;

That way you're counting from 0 . If you don't initialize it, its initial value will be whatever 4 B of garbage data happen to be in that location of your computer's RAM when you allocate the memory, which in this case was around 135 million.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM