Reputation: 10425
I'm trying to write a simple function that will pause my console.
Simple enough, but I want it to work in both cases: when the stream is empty, you just use std::cin.get();
or std::getchar();
; and when the stream is not empty, if you have inputted anything during the course of the program, you would have to use std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin.get();
;
So, I wanna write a function which would handle both with a simple if
statement, if possible. Unfortunately I'm insanely bad with C++ streams
. I hope someone with more knowledge in the area can help or point out the obvious function I've missed. Thanks!
#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();
}
Upvotes: 0
Views: 3956
Reputation: 10425
void pause()
{
if (std::cin.rdbuf()->in_avail() > 0)
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
}
Upvotes: 1