首页 文章

如何在getline之后输入

提问于
浏览
0
#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;
}

问题是它没有在电子邮件地址后输入,程序忽略了在phno中输入,直接在emailadress后退出 .

1 回答

  • 0

    我对你的代码做了一些修改 .

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

    这是因为当你在int上使用 cin 时,它会将 \n 留在缓冲区中 . 当你以后打电话给 getline(cin,...) 时,你只是把剩下的 \n 吸了,这就算是你的整个"line."

    有一个工作示例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;
    }
    

相关问题