简体   繁体   中英

How to take input after getline

#include <iostream>
#include <string>
using namespace std;

struct Student
{
    int ID;
    long phno;
    string name;
    string depart;
    string email;
};

int main ()
{
    Student S1 ;

    cout << "\n=======================================================\n" ;

    cout << "Enter ID no. of student 1       : " ; cin >> S1.ID ;
    cout << "Enter name of student 1         : " ; getline(cin, S1.name) ; cin.ignore();
    cout << "Enter department of student 1   : " ; getline(cin, S1.depart) ; cin.ignore();
    cout << "Enter email adress of student 1 : " ; getline(cin, S1.email) ; cin.ignore();
    cout << "Enter phone number of student 1 : " ; cin >> S1.phno ;     

    return 0;
}

The problem is that it's not taking input after email adress the program is ignoring to take input in phno, directly exit after emailadress.

I made some slight modifications to your code.

Note that I only call cin.ignore() after I use cin directly on a variable ( cin >> S1.ID or cin >> S1.phno ).

This is because when you use cin on an int, it leaves the \\n in the buffer. When you later call getline(cin,...) you just suck up that leftover \\n , and that's considered your whole "line."

A working example is available here .

#include <iostream>
#include <string>
using namespace std;

struct Student
{
    int ID;
    long phno;
    string name;
    string depart;
    string email;
};

int main ()
{
    Student S1 ;

    cout << "\n=======================================================\n" ;

    cout << "Enter ID no. of student 1       :\n" ;
    cin >> S1.ID ; 
    cin.ignore();

    cout << "Enter name of student 1         :\n" ;
    getline(cin, S1.name) ; 

    cout << "Enter department of student 1   :\n" ;
    getline(cin, S1.depart) ;

    cout << "Enter phone number of student 1 :\n" ;
    cin >> S1.phno ;
    cin.ignore();

    cout << "Enter email adress of student 1 :\n" ;
    getline(cin, S1.email) ;    

    cout << endl << endl;

    cout << S1.ID << endl << S1.name << endl << S1.depart << endl << S1.phno << endl << S1.email << endl;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM