使用 cin.ignore 和 cin.clear CPP 时的奇怪行为

Weird behavior when using cin.ignore and cin.clear CPP

我了解到 cin.clear() 清除错误标志,因此 cin 操作将正常工作,并且 cin.ignore() 从流中提取字符。 所以我尝试了这段代码:

#include <iostream>
#include <string>
int main()
{
    std::string s;
    std::cin >> s;
    std::cout << s;
    std::cin.clear();
    std::cin.ignore(1000, '\n');
    std::getline(std::cin, s);
    std::getline(std::cin, s);
    std::cout << s;
    system("pause");
    return 0;
}

效果很好。 对于三个输入:

I
AM
TRY

输出将是:

I 
TRY

但是如果我把它改成:

#include <iostream>
#include <string>
int main()
{
    std::string s;
    std::cin >> s;
    std::cout << s;
    std::cin.clear();
    std::cin.ignore(1000, '\n');
    std::getline(std::cin, s);
    std::cin.clear(); // New code
    std::cin.ignore(1000, '\n');  // New code
    std::getline(std::cin, s);
    std::cout << s;
    system("pause");
    return 0;
}

我需要输入四个输入!

当我添加上面的代码时,我需要输入:

I
AM
NOW
TRY

要获得相同的输出?由于某种原因,它需要多输入一个。

考虑到你每次都输入I AM TRY NOW

#include <iostream>
#include <string>
int main()
{
    std::string s;
    std::cin >> s;
    std::cout << s; //-> outputs "I"
    std::cin.clear();
    std::cin.ignore(1000, '\n');//consumes all that follows "I"
    std::getline(std::cin, s); //-> get the whole "I AM TRY NOW" inside s
    std::cin.clear(); 
    std::cin.ignore(1000, '\n');  //Your cin is empty (because you took the whole line with getline(), not just part of the line, the stream has no character left in it and this cin.ignore() call is the reason you need 1 more input, because calling cin.ignore() en empty stream does that.
    std::getline(std::cin, s); //-> overwrites the previous std::getline(std::cin, s);
        std::cout << s; //outputs the whole line : "I AM TRY NOW"
        system("pause");
        return 0;
}

因为您在一个空流上调用 cin.ignore(1000, '\n');,所以您会通过第二个代码示例获得更多输入。 试试这个

int main()
{
    std::string s;
    std::cin.ignore(1000, '\n');  // New code
system("pause");
}

它需要输入,而这 :

int main()
{
    std::string s;
    cin >> s;
    std::cin.ignore(1000, '\n');  // New code
    system("pause");
}

如果你输入 I 也需要一个输入,换行符将被丢弃,如果你输入 I AM TRY 然后 AM TRY 并且换行符将被丢弃

int main()
{
    std::string s;
    cin >> s;
    std::cin.ignore(1000, '\n');  // New code
    std::cin.ignore(1000, '\n');  // requires second input
    system("pause");
}

将需要两个输入,因为在第二次 cin.ignore 调用时,有一个空的 cin stram。