![](/img/trans.png)
[英]How can I check the current ostream dec/hex mode when writing my own streaming operator?
[英]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();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); std::cin.get();
;
所以,我想寫一個函數,如果可能的if
,它可以用一個簡單的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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.