#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 回答
我对你的代码做了一些修改 .
请注意,我直接在变量(
cin >> S1.ID
或cin >> S1.phno
)上使用cin
后才调用cin.ignore()
.这是因为当你在int上使用
cin
时,它会将\n
留在缓冲区中 . 当你以后打电话给getline(cin,...)
时,你只是把剩下的\n
吸了,这就算是你的整个"line."有一个工作示例here .