custom countdown using while

Jul 18, 2009 at 9:38pm
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;
}
Jul 18, 2009 at 9:55pm
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.
Jul 18, 2009 at 9:56pm
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.
Jul 18, 2009 at 9:59pm
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/
Jul 18, 2009 at 10:05pm
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
Jul 18, 2009 at 10:20pm
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 
Jul 18, 2009 at 10:38pm
true - i havent taken it into consideration
Jul 19, 2009 at 3:01am
Conforming implementations are not required to return any useful information other than zero for in_avail().
Jul 19, 2009 at 8:55pm
I barely ever use it, but I am curious.
Would you mind giving me an example?
Thank you in advance.
Last edited on Jul 19, 2009 at 8:55pm
Jul 19, 2009 at 11:52pm
See here for more about in_avail
http://www.daniweb.com/forums/thread90228.html

Alas.
Topic archived. No new replies allowed.