1

I'm a beginner and I copied this code from a book but it doesn't work because when I enter EOF, the program instead of quitting the while loop prints the default message twice. It is like a hour that i search for a solution but nothing that i've tried works, thanks for help. the program is supposed to count the number of each kind of grades.

#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <math.h>
#include <ctype.h>

using namespace std;


int main()
{ 

    int grade,
        aCount = 0,
        bCount = 0,
        cCount = 0,
        dCount = 0,
        fCount = 0;



    cout << "Enter the letter grades (EOF to quit) ->>";

    while ((grade = cin.get()) != 'EOF')  {

        switch (grade) {

        case 'A':
            ++aCount;
            break;

        case 'B':
            ++bCount;
            break;

        case 'C':
            ++cCount;
            break;

        case 'D':
            ++dCount;
            break;

        case 'F':
            ++fCount;
            break;

        case '\n':
        case '\t':
        case ' ':
            break;

        default :
            cout << "Invalid letter grade entered. Enter a new grade." << endl;
            break;

        }
    }
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

2 Answers2

6

The documentation for cin.get() tells us that the return condition you are looking for is EOF.

while ((grade = cin.get()) != EOF)  {

That's it — no quotation marks! It's a macro that expands to an integer. What you did was to write a "multi-byte character literal" 'EOF', which has implementation-defined meaning and no real relevance here.

Either you copied from the book wrong, or the book is wrong.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

the docs say: cin.get() extracts a single character from the stream as unformatted input.

when you enter -1 it's considered as 2 seperate inputs - and 1 both of them dont match any case that's why the default message get printed twice and the condition to exit the while loop is never met

Unlike files console doesnt have an EOF flag. Nonetheless you can simulate it by typing Ctrl + Z

A simple workaround is to change the condition, something like entering 'X' exits the loop while ((grade = cin.get()) != 'X')

taha
  • 997
  • 9
  • 17