I was wondering why my code is having problems once it comes out of
the do-while loop below. The user types while the time is less than 5
secs. At this point, the loop ends and the user is told they have
finished the essay. However, the next screen clear and "You have
completed the experiment" are skipped passed. This seems to be
because if the user is typing as the 5s ends, the keypresses somehow
keep getting inputted and are used in the next 'press a key', which
is therefore passed without being seen. I tried emptying the input
and output streams by flushing/ignoring and things, but this didn't
solve the problem.
time_t seconds1, seconds2;
int c;
string essay;
seconds1 = time (NULL);
do {
if(kbhit()) {
c = getch();
essay.append(1,c);
cout << char(c);
}
seconds2 = time (NULL);
} while(seconds2 - seconds1 <= 5); // max time in seconds
system("cls");
cout << "You have completed the essay.\n";
Sleep(3000);
system("cls");
cout << "You have completed the experiment.\n";
cout << "Press a key";
getch();
cout << endl;
Ideally, I would like the program to wait at the 'sleep' command as
it does, and at that point, all previous inputs and things should be
erased so that none are stored for the following getch().
Please can you suggest how I stop any accidental typing at the 5s
mark from interfering with the rest of the program.
Thanks,
Robin.