Array Structure

When I run the program it always skips the input for the name, can someone help me out?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  #include<iostream>
#include<string>
#include<sstream>
using namespace std;
 struct studentrec{
           string name;
           int id;
           int quiz;
           }record[3];
int main ()
{   
    int i;
    double avg;
    
    cout << "Enter student record:" << endl;
    cout << "ID:" ;
    cin >> record[0].id;
    cout << "Name:" << endl;
    getline(cin, record[0].name);
    
    for(i=0;i<3;i++)
    {
     cout << "Enter quiz " << i+1 << ": " ;
     cin >> record[i].quiz;
    }    
   cout << endl;
   cout << endl;
   cout << endl;
   cout << endl;
   
   cout << "Student Record: " << endl;
   cout << "ID:  " << record[0].id << endl;
   cout << "Name: " << record[0].name << endl;
   
   for(i=0;i<3;i++)
   {
    avg=record[i].quiz+avg;   
   }
   avg=avg/3;
   cout << "Grades: " << avg << endl;
   if(avg<75)
   cout << "Failed " << endl;
   else
   cout << "Passed " << endl;
 
   system("pause");
   return 0;  
}
The problem is being caused because the extraction operator>> leaves the end of line character in the input buffer and when getline() encounters this character stops processing. So to fix the problem you need to remove this character. something like: getline(cin >> ws, record[0].name);.

By the way why are you creating an array of your structure, as a global variable no less, but only trying to retrieve the name of the first record. Perhaps you should have a normal single instance of your structure that has an array of quizzes instead.

Thanks man!

I couldn't figure out what the problem was so I was placing the structure in and out the main function and a lot of other stuffs trying to figure out where the hell did I go wrong LOL.

Can I ask what the ws is for? And correct me if im wrong, is the end of line character this one? '\0'

EDIT:
A follow up question, if my code is something like
cout
for loop (3x)
{cin}
how do i make it so that my cin goes on the same line as my cout ?
Last edited on
Can I ask what the ws is for?

When used with an input stream it tells the input stream to consume and discard all leading whitespace.

And correct me if im wrong, is the end of line character this one? '\0'

No that is more commonly referred to as the end of string character. The end of line character is '\n'.

how do i make it so that my cin goes on the same line as my cout ?

If you don't issue the end of line character or use endl the next operation will happen on the existing line. In your loop if you press the enter key the cursor will go to the next line. If you're using the extraction operator you can enter multiple items on the same line without using the enter key by just pressing the space key until the last entry.



Last edited on
Topic archived. No new replies allowed.