我了解到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。

09-07 03:12
查看更多