problem in overloaded cin

when i run the program i'm writting if i type 2 words for the name then the cin for grade is skipped and when cout 0 is displayed

1
2
3
4
5
6
7
8
9
istream& operator>> (istream &in, Alumno &al)
{
    cout << "\ntype student Id: \n";
    in >> al.id;
    cout << "\nType student name: \n";
    in >> al.name;       // when i write more than 1 word
    cout << "\ntype student grade: \n";
    in >> al.grade;      // this one is skipped
    return in;


i tried changing the name cin for a getline but then when i run it is skipped so i end up with no cin for name

1
2
3
4
5
6
7
8
9
10
istream& operator>> (istream &in, Alumno &al)
{
    cout << "\ntype student Id: \n";
    in >> al.id;
    cout << "\nType student name: \n";
    getline(in , al.name);     // now this one is skipped 
    cout << "\ntype student grade: \n";
    in >> al.grade;           // and this works
    return in;
}



how can i fix it ?
thanks


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
50
51
52
53
54
55
56
57
#include <iostream>
#include <string>
using namespace std;

class Alumno
{
    private:
        int id;
        string name;
        int grade;
    public:
        void showId()
        {
            cout << " : ";
        }
        void showName()
        {
            cout << " : ";
        }
        void showGrade()
        {
            cout << " : ";
        }
        void average()
        {
            
        }
        
        friend ostream& operator<< (ostream &out, Alumno &al);
        friend istream& operator>> (istream &in, Alumno &al);
};
ostream& operator<< (ostream &out, Alumno &al)
{
    out << "Id: " << al.id << " name: " << al.name <<
           " grade: " << al.grade << "\n" ;
    return out;
}
istream& operator>> (istream &in, Alumno &al)
{
    cout << "\ntype student Id: \n";
    in >> al.id;
    cout << "\nType student name: \n";
    in >> al.name;
    cout << "\ntype student grade: \n";
    in >> al.grade;
    return in;
}
int main()
{
    Alumno alumn[35];
    cin >> alumn[1];
    cout << alumn[1];


    return 0;
}
it works if i put cin.ignore(); after the first cin
but is there any better way to solve it ?
may be a better way to write the code ?

1
2
3
4
5
6
7
8
9
10
11
istream& operator>> (istream &in, Alumno &al)
{
    cout << "\ntype student Id: \n";
    in >> al.id;
    cin.ignore();        // this makes it work
    cout << "\nType student name: \n";
    getline(in , al.name);    
    cout << "\ntype student grade: \n";
    in >> al.grade;           
    return in;
}
Last edited on
Topic archived. No new replies allowed.