Reputation: 679
OK so im trying to learn some C. I am trying to write a program that will have a number and have the user ask a number.
I have everything done accept after the it guesses it asks the user if they want to play again. If they type Y or y then the the game will restart and if they type 'N' or 'n' then the program will terminate.
what im trying to do
int main(){
while(playAgain == 'y' || 'Y') {
*playing code here*
printf("would you like to play again");
scanf("%s", &playAgain);
}
it doesnt break... at all... ever, no matter what i type in. What am I doing wrong?
Upvotes: 2
Views: 134
Reputation: 51
You have to fix some things in the code:
char playAgain = 'y';
while(playAgain == 'y' || playAgain == 'Y') // *1
{
//*playing code here*
printf("would you like to play again? ");
scanf("%s", &playAgain); //*2
}
*1 You have to put each condition splitted by AND or OR (&& or ||).
*2 The correct format for use scanf parameters is using "%", not "$". Check more information of use here: http://www.cplusplus.com/reference/cstdio/scanf/
With your code fixed, the loop while will repeat always that the user type any word starting with 'y' or 'Y', for example 'Yellow' will do in this code that restart the loop. If you want to control the full string introduced, you will have to use a char array or string and compare it with an auxiliar function, something like this:
bool compareArrays(char* str1, char* str2, int lenght)
{
int i;
for (i=0; i<lenght; ++i)
if (str1[i] != str2[i]) return false;
return true;
}
Upvotes: 1
Reputation: 511
I'm guessing the type here for playAgain is a char?
You're not using scanf correctly. http://www.cplusplus.com/reference/cstdio/scanf/
scanf with %s expects to read a string. In C a string is char*, so it will write playAgain with the pointer value discarding the top bits. This will pretty much be a random value and the comparison will fail. If you want to keep playAgain as a character you should use %c.
By the way it is % not dollar.
Alternatively you can implement playAgain as a string. In that case you can do:
int main(){
char playAgain[buffer_size];
do{
/*playing code here*/
printf("would you like to play again");
scanf("$s", &playAgain);
lower_case_string( playAgain); // Call a function for changing string to lower case
}while( !strcmp( "yes", playAgain) || !strcmp( "y", playAgain );
}
Upvotes: 2
Reputation: 2872
The issue here (apart from the things in the comments) is your conditional semantics. You want playAgain == 'y' || 'Y'
to be interpreted as playAgain equals 'y' or playAgain equals 'Y'
.
Instead, it's being parsed as (playAgain equals 'y') or ('Y')
. Since true is defined as non-zero, and 'Y'
is non-zero (ASCII value of 131), 'Y'
is always true, and your conditional is always true. You want:
while (playAgain == 'y' || playAgain == 'Y')
Upvotes: 3