-
timer in c++?
Another little program/game I'm working on in c++ is, how many times can you press the 'Enter' key in 20 seconds. I've made it output a higher number every time you press enter, but I haven't made the timer. How do you do that?
Here's the code I have allready.
Code:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int press = 0;
for(press = 0; press < 1000; press++)
{
cin.get();
cout << press << endl;
}
return 0;
}
How do I get the timer in this code?
Greatfaith.
-
A naïve start might be like this.
Code:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int press = 0;
time_t now, start = time(0);
while ( (now = time(0)) < start + 20 )
{
cin.get();
cout << ++press;
}
return 0;
}
-
...and as I'm sure Dave knows the problem with his "naive program" is that you could just let it sit there never pressing anything and it will never end. I would suggest using conio.h and kbhit()
Code:
#include <iostream>
#include <ctime>
#include <conio.h>
using namespace std;
int main() {
int press = 0;
time_t now, start = time(0);
while ( (now = time(0)) < start + 20 ) {
if (kbhit()) { // Wait for input
if (getch() == 13) { // Compare that input to Enter
cout << ++press << endl;
}
}
}
cout << "You hit ENTER " << press << " times.";
cin.get(); // You should put this in a check to see it isn't
// ENTER otherwise you pound your key into
// closing the program
return 0;
}
-
If you want to assume that the OP is using an OS/Compiler which supports such functionality....
-
How do I put in a check to see if another key is pressed, other than ENTER?
cin.get(SPACE); ??????
-
The get() function doesn't return as soon as any key is pressed. It returns when enter is pressed, and you can press whatever you want before that. If you want a function that will return as soon as any key is pressed, you're going to have to go outside the standard. The most popular method is found in conio.h, which is not standard but it is common.
Code:
#include <conio.h>
...
char mychar = getch();
mychar will then hold the character that was pressed. If the person pressed space it will contain, " ".
-
hmm i knew it went something like this :)
Code:
#include <time.h>
#include<stdio.h>
int main(void){
long start,end;
start=clock();
do
end=clock();
while((end-start)/CLK_TCK<20);
}
to convert into seconds the time spent is divided by CLK_TCK which is defined in <time.h> header ...uhm it's kind of outdated but hopefully you'll still have it in your library :) check it out.