如何检查i/ostream是否为空

How to check if i/ostream is empty?

本文关键字:ostream 是否 何检查 检查      更新时间:2023-10-16

我试图写一个简单的函数,将暂停我的控制台。

足够简单,但我希望它在两种情况下都能工作:当流为空时,您只需使用std::cin.get();std::getchar();;当流不为空时,如果您在程序过程中输入了任何内容,则必须使用std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); std::cin.get();;

所以,如果可能的话,我想写一个函数来处理一个简单的if语句。不幸的是,我对c++ streams非常糟糕。我希望在该领域有更多知识的人可以帮助或指出我遗漏的明显功能。谢谢!

#include <iostream>
#include <limits>
void pause()
{
    if (std::cin.eof()) //I don't know what I'm doing here. Don't judge, lol
    {
        std::cin.get();
    }
    else
    {
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
        std::cin.get();
    }
}
int main()
{
    int i = 0;
    std::cin >> i;          //if I comment this line, I would have to press enter twice
    std::cout << "Hello world!";                         //to close the console
    pause();
}
void pause()
{
    if (std::cin.rdbuf()->in_avail() > 0)
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    std::cin.get();
}