如何在getline之后获取输入

How to take input after getline

本文关键字:获取 输入 之后 getline      更新时间:2023-10-16
#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;
}

问题是它没有在email地址之后接受输入,程序忽略了在phno中接受输入,直接在email地址之后退出。

我对你的代码做了一些轻微的修改。

注意,当我在变量(cin >> S1.IDcin >> S1.phno)上直接使用cin后,我调用cin.ignore()

这是因为当你在int上使用cin时,它会将n留在缓冲区中。当你稍后调用getline(cin,...)时,你只需要吸收剩下的n,这被认为是你的整个"行"。"

这里有一个工作示例。

#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;
}