Hi,
The problem is that we need to clear the input buffer before using gets() because gets() read anything in the input buffer until it encounters a new line or return character. Although it works correctly, it is unsafe to use gets() if the input is bigger than the array can be stored, it writes over the array as we are not expected. Good luck with your program.
Here is the modified code:
#include
#include
using namespace std;
int main ()
{ char str[10]="ABCDE FG", ch, solve[10], guess[10];
int select;
cout << "Word Puzzle\n"
<< "===========\n\n\n";
for(int i=0; str[i]!='\0'; i++)
if(i!=5)
cout << "_ ";
else
cout << " ";
cout << "\n\n\n\n";
do {
cout << "1) Enter a character\n2) Solve the puzzle\n3) Exit\n";
cin >> select;
if(select==1) {
cout << "\nPlease enter a character: ";
cin >> ch;
ch=toupper(ch);
cout << "\n\n";
for(i=0; str[i]!='\0'; i++)
if(ch==str[i])
guess[i]=ch;
else if(str[i]==' ')
guess[i]=str[i];
for(i=0; str[i]!='\0'; i++)
if( guess[i]==str[i])
cout << guess[i];
else
cout << "_ ";
guess[i]='\0';
}
else if(select==2) {
cout << "\nSolve the puzzle:";
// To clear the input buffer
fflush(stdin);
gets( solve);
if( strcmp(solve, str)!=0 )
cout << "Your answer is wrong...";
}
else
return 0;
cout << "\n\n";
} while(strcmp(solve, str)!=0 && strcmp(guess, str)!=0);
if( strcmp(solve, str)==0 || strcmp(guess, str)==0)
cout << "Well done!!! You got the correct answer!!!\nThe answer is ABCDE FG.";
cout << "\n\n\n";
return 0;
}