But some of them were only suitable on Windows (ex. system("Pause" ), ) and others were too complex. So I decided to use "Press enter to continue", which is more easy, instead, for my program.
The way I chosen was using cin.ignore(). In c++ reference, the function is described:
Extracts characters from the input sequence and discards them.
The extraction ends when n characters have been extracted and discarded or when the character delim is found, whichever comes first. In the latter case, the delim character itself is also extracted.
I wrote a subroutine as below:
void PETC() { //press enter to continue
cout << "Press ENTER to continue...\n";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
It worked fine until I put the subroutine in switch conditional judgement, which looks like:
char cmd;
.
.
.
cin >> cmd;
switch (cmd) {
case '1':
.
.
PETC();
break;
case '2':
.
.
PETC();
break;
}
PETC() dose not work! It shows "Press ENTER to continue...", but it does not wait for me to press enter. I put it away for two days because it was Chinese New Year :p. Two days latter, I opened my code and worked it for a morning. I thought it might because the cin before switch (and otherwhere) leaves return in input buffer. My solution was modifying the PETC() as:
void PETC() { //press enter to continue
cout << "Press ENTER to continue...\n";
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
And it worked!
沒有留言:
張貼留言