dimanche 22 février 2015

Simple guessing game continuing with any other letter other than the declared variable Y/N


I am a aspiring developer and I am just learning my first language which is C++. I was creating a simple guessing game using the things I've learned off of the internet and YouTube. Pretty much the computer randomly generates a number between 0 and 5 and you'll have to enter which number you would be the correct one.


The problem would be that after the program asks for your name ( Which isn't stored) then would ask if you would like to play a game which asks for a y or a n. y continues and n closes the program.


Y is suppose to continue the game but if I would put another letter, g for example, it would continue with the game. How would I fix the code to only allow the variable "y/Y" to continue the game?


Thank you for your help!


Below is the code.



#include <iostream>
#include <Windows.h>
#include <cmath>
#include <ctime>
#include <string>

using namespace std;

int main()
{
int num, numrand;
char yn;
string name;
srand(time(NULL));
cout << "Welcome to the program and please enter your name:";
cin >> name;
while (true)
{
cout << "Hello " << name << " do you want to play a game? (y/n): ";
cin >> yn;
if (yn == 'n' || yn == 'N')

return 0;
if (yn == 'y' || yn == 'Y');
break;
//If any other letter is used then it will continue. how to fix?
}

while (true)
{
cout << "computer will imagine one number from 0 to 5 and you will be given the task to guess it: ";
cin >> num;
numrand = rand() % 6;
if (numrand == num)
cout << "You Win!" << endl;
else if (num == -1)
break;
else
cout << "You Lose! The computer imagined the number: "<< numrand << endl;

}


system("pause");
return 0;
}



Aucun commentaire:

Enregistrer un commentaire