|
Hello there, new to both C++ and this forum and was wondering if anyone could help me. I've been workin g through the tutorials at www.cprogramming.com and to test what i've learnt so far have made a simple guessing game, where a random number is generated and then two people try to guess and obviously the closest wins. My problem is that i've tried to make an option to reply by pressing 'y', however, tghe program loops whatever the input. I've also tried to do away with that input, and set it so the condition of 'Do while' is false and yet it still loops. here is the code...
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int a; //player 1 guess
int b; //player 2 guess
int d; // player 1 out by
int e; // player 2 out by
int x = 5; // play again variable
do
{
int c = rand()%10 + 1;
cout<<c<<endl;
cout<<"Player 1 guess the number\n";
cin>> a;
cin.ignore();
cout<<"Player 2 guess the number\n";
cin>> b;
cin.ignore();
if ( c < a ) {
d = (a - c) ;
}
else { d = (c - a) ;}
if ( c < b ) {
e = (b - c) ;
}
else { e = (b - a) ;}
if ( d < e ) {
cout<<"Player 1 was closer\n";
}
else {cout<<"Player 2 was closer\n";}
cout<<"Play again? (Y/N)\n";
cin>> x;
}
while ( x = 'y' );
cout <<x<<endl;
cin.get();
}
<Added>
Oh yeah, also how do I get it so pressing 'y' repeats the loop, without having to press return, and obviously so pressing n quits the program?
|
|
|
First thing I noticed, is the conditional at the end of your code:
while ( x = 'y' )
or did you mean:
while ( x == 'y' ) ?
|
|
|
|
|
|
|
|