如何检查i/ostream是否为空
How to check if i/ostream is empty?
我试图写一个简单的函数,将暂停我的控制台。
足够简单,但我希望它在两种情况下都能工作:当流为空时,您只需使用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();
}
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- ostream过载时的缓冲区冲洗
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 是否可以为算术表达式重载 ostream 运算符
- 检查是否已写入给定的 ostream 对象
- 检查std::ostream中是否序列化了某些内容
- 从空缓冲区构造“std::ostream”是否有效
- 如何检查i/ostream是否为空
- c++或库中是否存在null std::ostream实现?
- C++流插入运算符的返回类型是否需要是std::ostream
- 如何检测类型是否可以流式传输到 std::ostream