cin与getline()的区别:
getline()中的结束符,结束后,结束符不放入缓存区;
cin的结束符,结束后,结束符还在缓存区;
所以在使用 cin 后若要使用 getline() 必须要把前面cin遗留的结束符处理掉,解决方法为:在使用getline()之前,加入一行getline()来处理cin留下的结束符
|| 如;
#include<iostream>
using namespace std;
int main(){
int x;
string a,b;
cin>>x;
getline(cin,a);
getline(cin,b);
cout<<x<<endl;
cout<<a<<endl;
cout<<b<<endl;
return 0;
}
输入;3 回车 abc
3
abc
3
abc
--------------------------------
Process exited after 6.016 seconds with return value 0
请按任意键继续. . .
-->> 回车被读入字符串a中;
如;
#include<iostream>
using namespace std;
int main(){
int x;
string a,b;
cin>>x;
getchar();
getline(cin,a);
getline(cin,b);
cout<<x<<endl;
cout<<a<<endl;
cout<<b<<endl;
return 0;
}
输入;3 回车 abc eee
3
abc
eee
3
abc
eee
--------------------------------
Process exited after 10.25 seconds with return value 0
请按任意键继续. . .
-->>此时cin缓存区的回车被getchar()吸收;
或者可以 cin>>n>>a>>b; 同类型的输入格式回车会一直存在缓存区内(本人这样理解)