getline 语句未获取输入
getline statement is not getting the input
//class
class student
{
public:
int rno;
string name;
int marks;
int ran;
void getinfo()
{ a:
cout<<"\t \tenter the roll number"<<endl;
cin>>rno;
cout<<"\t \tenter the name"<<endl;
getline(cin,name);
cout<<"\t \tenter the marks"<<endl;
cin>>marks;
}
void showinfo()
{
cout<<"\t"<<ran<<"\t "<<rno<<" \t\t"<<name<<" \t\t"<<marks<<endl<<endl;
}
};
当我在为 roll no 提供输入后在控制台中获取对象的输入时,它正在打印 "enter the name" 然后没有任何机会提供输入,它显示下一个打印语句 "enter the marks"。 getline 语句没有从控制台获取输入有什么原因吗??
cin
将在缓冲区中留下新行。因此,当您从 cin
得到 rno
时,cin
缓冲区中实际上还剩下一个 \n
。当你去阅读名字时,它只是抓取 \n
并立即 returns。
在第一个 cin
之后执行类似 cin.ignore();
的操作应该会清除缓冲区并允许您正确读取用户输入。
//class
class student
{
public:
int rno;
string name;
int marks;
int ran;
void getinfo()
{ a:
cout<<"\t \tenter the roll number"<<endl;
cin>>rno;
cout<<"\t \tenter the name"<<endl;
getline(cin,name);
cout<<"\t \tenter the marks"<<endl;
cin>>marks;
}
void showinfo()
{
cout<<"\t"<<ran<<"\t "<<rno<<" \t\t"<<name<<" \t\t"<<marks<<endl<<endl;
}
};
当我在为 roll no 提供输入后在控制台中获取对象的输入时,它正在打印 "enter the name" 然后没有任何机会提供输入,它显示下一个打印语句 "enter the marks"。 getline 语句没有从控制台获取输入有什么原因吗??
cin
将在缓冲区中留下新行。因此,当您从 cin
得到 rno
时,cin
缓冲区中实际上还剩下一个 \n
。当你去阅读名字时,它只是抓取 \n
并立即 returns。
在第一个 cin
之后执行类似 cin.ignore();
的操作应该会清除缓冲区并允许您正确读取用户输入。