Reputation: 3
The point of this program is for the user to enter the grade of a certain amount of students up to 50, from a range of grades A,B,C,D, or F. At the end, the program is then supposed to show how many students got each grade. Whenever I test the following code, whatever I input for the for loop repeats every time, such that if I input for it to do the grades 3 students, whatever letter I enter for student 1 will be the same grade for every student, so if one student has an A, they all will have an A. I also have to use arrays for this program because it's for college. Sorry if there's not enough information, this is my first time posting.
#include<iostream>
#include<iomanip>
#include<string>
void gradeTotals();
using namespace std;
int x,z,a=0,b=0,c=0,d=0,f=0,i=0;
char grade[50];
int main()
{
cout<<"Please enter the number of students"<<endl;
cin>>x;
for (i=0;i<x;i++)
{
int y;
y=i+1;
cout<<"Please enter a letter grade of A,B,C,D, or F for student "<<y<<endl;
cout<<"All grades must be uppercase"<<endl;
cin>>z;
grade[i]=z;
gradeTotals();
}
}
void gradeTotals()
{
if (grade[i]=='A')
{
a++;
}
else if (grade[i]=='B')
{
b++;
}
else if (grade[i]=='C')
{
c++;
}
else if (grade[i]=='D')
{
d++;
}
else if (grade[i]=='F')
{
f++;
}
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
cout<<f<<endl;
}
Upvotes: 0
Views: 84
Reputation: 1006
The problem lies in having your input variable as an int
, take in a char
.
What happens is that when you perform cin >> z;
, the character that was input by the user is recognized as an invalid input by the >> operator
and therefore does not extract the character.
As such, z does not get any value, the character stays in the stream, and the >> operator
continues to fail to extract the character until the loop ends.
Therefore, you can solve your problem by making your input variable a char
instead.
Here's a link to help you better understand how to avoid such problems in the future.
Thank you for reading.
Upvotes: 0
Reputation: 10894
It looks like your if
statements are not doing what you expect. For instance:
if (grade[i]='B')
{
// This code will *always* execute
}
You ought to be using the double equals ==
to compare a value, and a single equals =
to assign a value.
(Edit after additional code change)
Inside the for-loop, you are trying to use cin
to read in a single character. However, since the z
is an integer, cin
is looking for a valid integer, which does not happen to include 'A' or 'B', etc.
Perhaps you should try using a getline()
or get()
.
Upvotes: 0