custom countdown using while

someone knows why this closes after i've inserted a number?

#include <iostream>
#include <limits>
using namespace std;

int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;

while (n>0) {
cout << n << ", ";
--n;
}

cout << "FIRE!\n";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
The extraction operator >> leaves whitespace in the stream. So your program runs all the code as it should, then when it reaches the cin.ignore() that you have to keep the console running, the whitespace that was left in the stream gets ignored and your program closes.
Because you instert nr + ENTER or '\n' when you enter your number.
So the cin.ignore reads your newline, which you entered at cin >> n; by pressing ENTER.
You have to clear your buffer first or to use another cin.ignore.
If you use getline to get input is better and you won't have to clear the buffer: http://www.cplusplus.com/forum/articles/6046/
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
As i know the first parameter of cin.ignore(..) method stands for maximum number of characters to ignore, but if you put that one mentioned above (maximum number of characters in a specific type - here integer) there won't be any input limitand the method passes all characters till its equal to the 2ndparameter - here "/n")

Tevsky and jmc already wrote about that

I think you can use cin.ignore(2); That should work fine in your example
cin.ignore(2); won't always work (e.g. input = '5 \n').
Use Bazzy's suggestion or clear the buffer.
You can cear the buffer e.g. like this:
1
2
3
cin.clear(); clear error flags
cin.ignore(cin.rdbuf()->in_avail()); // ignore all remaining characters
cin.ignore(); // wait for 1 character to ignore 
true - i havent taken it into consideration
Conforming implementations are not required to return any useful information other than zero for in_avail().
I barely ever use it, but I am curious.
Would you mind giving me an example?
Thank you in advance.
Last edited on
See here for more about in_avail
http://www.daniweb.com/forums/thread90228.html

Alas.
Topic archived. No new replies allowed.