为什么在"cin"后使用 "getline" 时需要 cin.ignore(),而多次使用 "cin" 时不需要?

Why is cin.ignore() necessary when using "getline" after "cin", but is not required when using "cin" multiple times?

本文关键字:cin 不需要 getline 为什么 ignore      更新时间:2023-10-16

在我所知,当cin之后使用getline()时,我们需要先在调用getline()之前先冲洗缓冲区中的newline字符,然后通过调用cin.ignore()

来做到这一点。
std::string name, address;
std::cin >> name;
std::cin.ignore(); //flush newline character
getline(std::cin,address);

但是,当使用多个cin时,我们不需要冲洗Newline字符。

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;

为什么?为什么在第一种情况下需要cin.ignore(),而不是最后一个?

,因为 getline()读取,直到给定std::istream的下一个newline targue the newline the std::istream::operator>>() skips> skips 任何whitespaces> newlines )。

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

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


考虑此代码段;

std::string a, b;
std::cin >> a;
std::getline(std::cin, b);

和此输入:

Stack Overflow<Enter>
Where developers learn.<Enter>

第一个cin语句将读取Stack一词,并留下一个空间,而Overflow<Enter>则落后。然后,它将由getline读取,所以

assert(b == " Overflow");

如果您在调用getline()之前插入std::cin.ignore(),则它将变成

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
}

输入输入

堆栈溢出

开发人员学习的地方。