-
getline and ignore
In the game I am making, the player is given a riddle and asked to enter an answer. The answer is two words, and so a normal cin>> will not work. I tried to use a getline (see code below) but I couldn't get it to work. Any help would be appreciated.
----------------------------
string RiddleAnswer;
"Block of text"
getch(); // To pause
clrscr();
gotoxy(1,2); // Spacing
"Riddle"
cout<< "Riddle answer: ";
cin.ignore(100, '\n');
getline(cin, RiddleAnswer);
----------------------------
As you can see I tried to use an ignore to ignore the getch, but the first time the user was asked to input something it took the key pressed (for the getch) as the entry, which would result in an incorrect answer to the riddle. How do I make this work??
Any help appreciated!
Kyoto Oshiro
-
Well, you could just get rid of getch. ;)
cin.ignore should work, but try replacing it with
while ( getchar() != '\n' );
and see how that works out. I'd have to see more of your code to give you a better solution since I don't feel like writing a test program. :D
-Prelude
-
You shouldn't have to ignore the getch(). It doesn't use a buffer, so wont leave characters in a streambuf to mess up getline().
-
Okay, I got it all fixed up and working now. I am using the free Borland C++ 5.5.1 compiler, and the getch() does disrupt the getline, normally taking the key pressed for the getch() and placing it into the getline (unlike what you had said Sorensen). So, here is what I did.
I decided to use the method you suggest Prelude. Thanks for that idea, I didn't want to have to do something drastic like change the riddle so it has a single word answer (and thus I could use cin>>). Anyways, the resulting code is below.
------------------------------
Pause(); // my function that uses getch() to pause the text so the
// player can read it all
clrscr();
gotoxy(1,2); // Just for spacing
"Riddle"
cout<< "Riddle answer: ";
while (getchar() != '\n');
getline(cin, RiddleAnswer);
while (getchar() != '\n');
------------------------------
The result is that the user enters their answer and hits any key (likely 'enter') twice. If the riddle is right, they pass that part of the quest (this is for a roleplaying game, btw) and if they fail they suffer damage (up to 10 tries at the riddle, then they die from the damage).
Anyhow, thanks for your help!!
Kyoto Oshiro
http://www.angelfire.com/realm2/horizon/files.html
Horizon Games