| re: problem with _kbhit and i/o exception handling
you are right, problem is due to abnormal condition of underlying
buffer. I didn't knew how to do that.
I checked with
cin.seekg( 0, ios::end );
it does solve the problem
thanks M,
mlimber wrote:[color=blue]
> vikas wrote:[color=green]
> > hi,
> > I want to generate random numbers in c++ (using vc++ 6.0) on hit of
> > enter. I am using _kbhit(), but don't know how to reset it, so that I
> > can use it again, can anybody help me with this.
> > code is say like following.
> >
> >
> > #include <iostream>
> > #include <conio.h>
> > #include <windows.h>
> > using namespace::std;
> >
> >
> > int main(int argc, char* argv[])
> > {
> > for(int i=0; i<10; i++)
> > {
> > cout << "hit enter to generate random number" << endl;
> > int ran1 = func1();
> > cout << "hit enter to generate random number" << endl;
> > int ran2 = func2();
> > }
> >
> > return 0;
> > }
> >
> >
> > int func1()
> > {
> > int ret;
> >
> > while(!_kbhit())
> > {
> > ret = rand()%10;
> > Sleep(10);
> > }
> > return ret;
> > }
> >
> >
> > int func2()
> > {
> > int ret;
> >
> > while(!_kbhit())
> > {
> > ret = rand()%20;
> > Sleep(10);
> > }
> > return ret;
> > }[/color]
>
> _kbhit is a non-standard Microsoft extension. You'll want to ask this
> question in a Microsoft newsgroup (e.g.
> comp.os.ms-windows.programmer.win32).
>
>[color=green]
> > There is another problem with I/O exception handling:
> > i tried to read an int correctly using following code. but in case of
> > exception it is caught but cin doesn't execute inspite of clearing it:
> >
> > int main(int argc, char* argv[])
> > {
> > int i;
> > bool check = false;
> >
> > cin.exceptions(ios_base::failbit);
> >
> > while(!check)
> > {
> > try{
> > cout << "enter a number: ";
> > cin >> i;
> > check = true;
> > }catch(ios_base::failure){
> > cin.clear();
> > }
> >
> > }
> >
> > return 0;
> > }[/color]
>
> What do you mean by "doesn't execute"? Why does the input fail? I'm
> guessing that you typed an invalid number (say, "xyz"), and clearing
> the state doesn't clear the underlying buffer (or something to that
> effect). Try adding this after the cin.clear():
>
> cin.seekg( 0, ios::end );
>
> Cheers! --M[/color] |