V
vikas
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;
}
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;
}
Thanks,
vikas
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;
}
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;
}
Thanks,
vikas