samedi 27 juillet 2019

Why is this not counting correctly?

I am reading text from a text file and need to know the number of characters in the file in total. I thought this should work but it always seems to be overcounting. For example I typed this into my text file:

thisisatestthisisa thisisa

And the program returned a total of 32.

int main() {

fstream inFile;
string inputString;

inFile.open("text.txt", ios::in);

unsigned int total = 0;
if (inFile) {
    while (inFile)
    {
        getline(inFile, inputString);

        unsigned int tempStringLength = inputString.length();
        total += tempStringLength;
    }
    cout << "total is: " << total << endl;
}
else {
    cerr << "Unable to open file text.txt";
    exit(1);
}

    return 0;

}

Aucun commentaire:

Enregistrer un commentaire