-1

I've been trying to read a text file with a loop. But for some reason, it never seems to get the integer values correct. I always end up with garbage values.

while(!file.eof())  // I've also tried other variations of this while loop, none of which worked either
    {
        // ifstream, string, char, string, int
        file >> name >> sex >> data >> score;  
        std::cout << name << std::endl;
        if (sex == 'F')
        {
            femaleAverage += score;
            femaleCount++;
        }
        else
        {
            maleAverage += score;
            maleCount++;
        }

        if (data.compare("CC"))
        {
            comAverage += score;
            comCount++;
        }
        else
        {
            uniAverage += score;
            uniCount++;
        }
    }

Here is what the text file looks like:

Bailey           M CC 68
Harrison         F CC 71
Grant            M UN 75
Peterson         F UN 69
Hsu              M UN 79
Bowles           M CC 75
Anderson         F UN 64
Nguyen           F CC 68
Sharp            F CC 75
Jones            M UN 75
McMillan         F UN 80
Gabriel          F UN 62 
ryan
  • 15
  • 1
  • 6

1 Answers1

0

Based on your if statements, it looks like sex is declared as char rather than char* or std::string. When you use file >> sex, it read the next character from the file into variable, without skipping over whitespace like it does for strings or numbers. As a result, sex gets the first space after the name, then it reads the sex field of the file into data and tries to read the data field into score.

You can use the std::skipws value to skip over whitespace before reading it.

You also shouldn't use while (!file.feof()), see Why is iostream::eof inside a loop condition considered wrong?.

So the code should look like:

while (file >> name >> std::skipws >> sex >> data >> score) {
    std::cout << name << std::endl;
    if (sex == 'F')
    {
        femaleAverage += score;
        femaleCount++;
    }
    else
    {
        maleAverage += score;
        maleCount++;
    }

    if (data.compare("CC"))
    {
        comAverage += score;
        comCount++;
    }
    else
    {
        uniAverage += score;
        uniCount++;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612