View Single Post
  #1 (permalink)  
Old October 10th, 2004, 01:21 AM
Slapworth Slapworth is offline
Registered User
 
Join Date: Oct 2004
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default C++ Beginner having (the usual?) getline problems

hi all -

I'm trying to use both cin and getline in the same program, which (from other forum posts here and elsewhere) seems fraught with peril.

The program is an exercise from Beginning C++, 2nd ed. You input up to ten names and grades, and return the average as well as lists of names and grades.

I'm getting a serious weirdness: I have to press ENTER two times to get the program to accept a name.

I've seen that a lot of people seem to have trouble with getline, but none of the solutions I saw elsewhere for their problems seemed to fit. (Or I'm having too much trouble understanding the problem to know when they might fit.)

I did get the Service Pack 6 for Visual Studio 6 -- since there had been a glitch in their getline implementation -- but rebuilding the program didn't show any improvement.

I hope someone can show me the error of my ways, or the way of my errors. The file is included below.

Thanks -- Slappy

-- main.cpp --

// Store first names and scores (0-100) of up to 10 students.
// Use a loop to prompt to enter users and grades.
// Calculate average grade (use a loop counter), display it
// and display the names and grades for all the students in the table.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main(void)
{
    const int max = 10;
// const char newLine = '\n';

    string name[max];
    string temp = "";
    int grade[max] = {0};
    int average = 0;
    int count = 0;
    int total = 0;
    char yesno = 0;

    cout << "This program averages the grades of up to 100 students." << endl;

    for (count = 0; count < max; count++)
    {
        cout << "Enter student's first name: ";
// cin >> name[count];

        getline (cin,name[count]);

// if (!cin) cout << "Stream is fouled!" << endl;


        cout << "Enter student's grade (0-100): ";
        cin >> grade[count];
        cin.ignore();
        total += grade[count];

        cout << "Enter another name? (y/n): ";
        cin >> yesno;
        cin.ignore();

        if (tolower(yesno) == 'n')
        {
            count++;
            break;
        }
    }

    cout << "The number of grades entered is " << count << "." << endl;
    cout << "The average grade is " << (total / count) << endl;

    cout << setw(20) << "Name" << setw(6) << "Grade" << endl;

    for (int i = 0; i < count; i++)
    {
        cout << setw(20) << name[i] << setw(6) << grade [i] << endl;
    }

    return 0;
}


Reply With Quote