C++ 为什么在使用“时需要使用cin.ignore()”;getline";“之后”;cin";,但在使用时不需要;cin";多次?

C++ 为什么在使用“时需要使用cin.ignore()”;getline";“之后”;cin";,但在使用时不需要;cin";多次?,c++,cin,getline,C++,Cin,Getline,据我所知,在cin之后使用getline()时,我们需要在调用getline()之前,首先刷新缓冲区中的换行符,然后调用cin.ignore() 但是当使用multiplecin时,我们不需要刷新换行符 std::string firstname, lastname; std::cin >> firstname; std::cout << firstname << std::endl; //no need to flush newline characte

据我所知,在
cin
之后使用
getline()
时,我们需要在调用
getline()
之前,首先刷新缓冲区中的换行符,然后调用
cin.ignore()

但是当使用multiple
cin
时,我们不需要刷新换行符

std::string firstname, lastname;

std::cin >> firstname;
std::cout << firstname << std::endl;

//no need to flush newline character

std::cin >> lastname;
std::cout << lastname << std::endl;
std::string firstname,lastname;
std::cin>>名字;
std::cout lastname;
std::cout因为
getline()
读取,直到给定
std::istream
中的下一个换行符,而
std::istream::operator>()
跳过任何空白(空格、制表符和换行符)

因此,当您读取整数或浮点数时,所有尾随空格都保留在输入流中。当您从控制台或终端读取数据时,键入数据并按Enter键,后者保留在流中,如果不清除,则会被
getline()
捕获

您不必清除它,因为下次读取
std::string
std::istream::operator>()
时会跳过空白


考虑这个代码段

std::string a, b;
std::cin >> a;
std::getline(std::cin, b);
这个输入:

堆栈溢出
开发者学习的地方。
第一个
cin
语句将读取单词
Stack
,留下一个空格和
Overflow
。然后它将被
getline
读取,所以

assert(b == " Overflow");
如果在调用
getline()
之前插入一个
std::cin.ignore()
,它将变为

assert(b == "Where developers learn.");
signed main(){
/*
*输入是下两行的
*堆栈溢出
*开发者学习的地方。
*有关cin的更多信息,请访问http://www.cplusplus.com/reference/istream/istream/ignore/
*/
字符串名称、地址;
cin>>名称;
//cin.ignore();
//cin.ignore(256,“\n”);
getline(cin,地址);

你能澄清一下包含字符是什么意思吗?你的意思是说
>
操作符也可以跳过一些字符吗?@UzairZia当你阅读带有
>
的字符时,除非你修改一些设置,否则你将无法捕捉空白。
assert(b == "Where developers learn.");
signed main(){
    /*
     * input is of next two lines
     * Stack Overflow<Enter>
     * Where developers learn.<Enter>
     * for more about cin.ignore visit http://www.cplusplus.com/reference/istream/istream/ignore/
     */
    string name, address;
    cin>>name;
    //cin.ignore();
    //cin.ignore(256,'\n');
    getline(cin,address);
    cout << address << endl;
    assert(address == " Overflow"); // breaks if using cin.ignore() or cin.ignore(256,'\n')
    assert(address == "Overflow"); // breaks if using cin.ignore(256,'\n') OR not using any
    assert(address == "Where developers learn."); // breaks if using cin.ignore() or not using ignore
}