For Loop to Collect 5 grades

Hi, while I know homework questions are shunned upon, I have been struggling for the past few days. With my code, I'm supposed to enter 5 grades using a for loop and calculate the average of the grades. But when I run the code I have, it doesn't allow me to input 5 grades. Here's my code. When I run it, it just outputs this: "Enter Grade 1: Enter Grade 2: Enter Grade 3: Enter Grade 4: Enter Grade 5:" and doesn't actually allow me to enter any grades. I am a complete beginner at coding so I might just be missing something crucial in my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>

using namespace std;

int main()
{
    int i, grades, avg;
    char studentName;

    cout << "Enter Student's First and Last Name: ";
    cin >> studentName;
    cout << endl;

    for (int i = 1; i <= 5; i++)
    {
        cout << "Enter Grade " << i << ": ";
        cin >> grades;

        
    }
Homework questions aren't shunned upon necessarily; we just generally don't like people asking us to do the whole assignment, and without putting any effort in themselves.

Two issues:

(1)
studentName should be a string, not an individual char.

You should change it to:
1
2
3
4
5
6
7
8
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string studentName;
    // ...
}


(2)
You didn't say what you were inputting as your studentName.
Since the prompt says "First and Last name", I assume you're typing something like "John Smith". The issue with this is that cin's >> operator is whitespace-delimited, so it only reads in the first word (John), leaving Smith still in the buffer, which then causes the next cin >> command to fail to parse an int.

instead of
cin >> studentName;
you want
getline(cin, studentName);
Last edited on
Thank you for going into detail on what I did wrong. I ran my code with the changes you recommended and it seems that it is working as intended, thank you!
Topic archived. No new replies allowed.