Why is this do while loop not working in C [duplicate] - c

This question already has answers here:
Why is my c != 'o' || c != 'x' condition always true? [duplicate]
(5 answers)
Closed 9 days ago.
I wanted to make a Tic-Tac-Toe game and this is the part where I get the user to input what symbol he wants to use (X or O). I created the do while loop to ensure that the characters given will be X or O.
char symbol;
do
{
printf("Choose Symbol X/O: ");
scanf("%c", &symbol);
} while ((symbol != 'X') || (symbol != 'O'));

symbol will always be not 'X' or not 'O'. You want '&&' here, and I added the space before %c to ignore the newline:
#include <stdio.h>
int main() {
char symbol;
do {
printf("Choose Symbol X/O: ");
scanf(" %c", &symbol);
} while (symbol != 'X' && symbol != 'O');
}
If you prefer you can use De Morgan's laws to negate the condition:
!(symbol == 'X' || symbol == 'O')
Which you could (after including string.h) write as:
!strchr("XO", symbol)

Related

Is there any time when scanf() function does not work properly? [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
How to do scanf for single char in C [duplicate]
(11 answers)
Closed last year.
I was trying to build the game of rock paper scissors in C. When I made it for playing one single time, it was working properly. But when I tried to make it run for multiple number of times using for loop, it failed to scan the value given by the user. It is running the code correctly when it is the eventh turn, i.e , 2nd,4th,6th and so on. But it fails to take the input when it is odd turn.
The code is given below:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int n;
printf("Enter the number of times you want to play rock paper scissors: ");
scanf("%d", &n);
for(int i=0;i<n;i++){
char c,p;
//creating random rps generator
int num;
srand(time(0));
num=rand()%3+1;
if(num==1){
c='r';
}
else if(num==2){
c='p';
}
else{
c='s';
}
//Taking input from the user
printf("Enter rock(r),paper(p) or scissors(s) : ");
scanf("%c",&p);
//Main code
if(c==p){
printf("It's a draw.\n");
}
else if((c =='r' && p =='p') || (c =='p' && p =='s') || (c =='s' && p =='r')){
printf("You win.\n");
}
else if((c =='p' && p =='r') || (c =='s' && p =='p') || (c =='r' && p =='s')){
printf("You lose.\n");
}
}
return 0;
}

C program loop repeats itself twice instead of once [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
I just started coding so sorry for the stupid question. This is C programming.
When the user inputs Y, the code runs as intended. If the user inputs N or any other character, the program loops but it repeats the same line twice for some reason.
For example:
Input: Y
Output: The game will now start!
Input: N
Output: Waiting...
Would you like to start the game? <Y/N>:
is not a valid response
Would you like to start the game? <Y/N>:
As you can see the line doubles, how do I fix this?
do {
printf("Would you like to start the game? <Y/N>: ");
scanf("%c", &cGameStart);
if (cGameStart == 'Y')
printf("\nThe game will now start!\n");
if (cGameStart == 'N')
printf("\nWaiting...\n\n");
if ((cGameStart != 'Y') && (cGameStart != 'N'))
printf("%c is not a valid response\n", cGameStart);
} while (!(cGameStart == 'Y'));
The comment are rather irrelevant to the problem.
The problem is the \n character left in the buffer by scanf. Eat it and it will work as intended.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char cGameStart;
do {
printf("Would you like to start the game? <Y/N>: ");
scanf("%c", &cGameStart);
if (cGameStart == 'Y')
printf("\nThe game will now start!\n");
if (cGameStart == 'N')
printf("\nWaiting...\n\n");
if ((cGameStart != 'Y') && (cGameStart != 'N'))
printf("%c is not a valid response\n", cGameStart);
fgetc(stdin);
} while (!(cGameStart == 'Y'));
printf("Game started\n");
}

How to use loops in terms of input (in C language)?

I've been trying to get this code to work but the loop does not seem to work? I am very new to C and I sort of get confused with the syntax of this language. However my loop is not functioning like how I want it to be. I want the if and else statement to work but no matter what input (right or wrong) it always outputs "thank you".
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c = 'Y' && 'y' && 'N' && 'n')
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}
int main(int argc, char* agrv[])
{
confirm();
return 0;
}
it won't ask to enter another output when the output is incorrect. It just keeps ending from the if statement, thus the loop is not running?
Please help.
There's nothing wrong with your loop - it's the if statement that's wrong.
This code compiles, but it does not do what you want it to do:
if (c = 'Y' && 'y' && 'N' && 'n')
= is an assignment; you need == to do a comparison
&& means "AND"; you need ||, which means an "OR"
You combine logical expressions, not constants with && or ||
The condition should be
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
Also note that when you read single characters with %c, your program "sees" all characters, including whitespace. This is a problem, because the '\n' left over in the buffer will be passed to your program before Y or N. To fix this, add a space before %c to your format string:
scanf(" %c", &c)
// ^
// |
// Here
Your code also ignores the first character that it reads. I think this is not intentional, so remove the call of scanf before the loop. You should also remove the second scanf from the loop, leaving the only call to scanf in the loop header.
int confirm()
{
char c;
printf("Confirm (y/n): ");
//scanf("%c", &c);// <---------- needless
while (scanf("%c", &c)) //<----while loop will do `scanf("%c",&c)`, so previous line should be remove.
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')// <- &&(AND); ||(OR). Also, be careful that don't be lazy, [c == 'Y' || 'y' || 'N' || 'n'] can't to communicate with computer
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}

C - While loop not exiting how expected with string input

I want to exit my do-while loop when the user enters "exit" from the command line. I'm trying to do it without using strcmp() but it's just not performing how I think it should. When testing it if the user enters e for the first character, or x for the second character, or i for the third, or t for the fourth character then the program exits. It's probably something simple that I'm missing. So can anyone explain why this isn't working how I'm expecting? Thanks.
#include <stdio.h>
#define FLUSH while(getchar() != '\n');
int main(){
char input[20] = {0};
printf("This is a string math program. Enter a string 9 characters or less"
" followed by an operater and finally another string 9 characters or less."
" There should be no spaces entered. To exit the program type exit.\n");
do{
printf("Input: ");
scanf("%s",input);
FLUSH
} while((input[0] != 'e') && (input[1] != 'x') && (input[2] != 'i') && (input[3] != 't'));
}
Let's talk about De Morgan's Law. This:
(input[0] != 'e') && (input[1] != 'x') && (input[2] != 'i') && (input[3] != 't')
is required to be true for your loop to continue. It is equivalent to this:
!(input[0] == 'e' || input[1] == 'x' || input[2] == 'i' || input[3] == 't')
So yes, your loop will stop when any character matches. Just use strcmp, but if you can't for some bizarre reason, just change the above logic.

Why does the message print twice?

I am creating a simple Tic Tac Toe for C, and here is a particular function which I am having a problem with. This is supposed to let the user select 'X' or 'O', and for the most art it works. However, if I enter a wrong symbol, it prints the statement:
"Invalid symbol, please re-enter: " twice.
Why and how can I fix this?
char assign(void)
{
char user;
printf("Would you like to be X or O (Enter your choice): ");
user=getchar();
while(user != 'X' && user != 'x' && user != 'O' && user != 'o')
{
printf("Invalid symbol, please re-enter: ");
user=getchar();
}
if(user == 'O' || user == 'o') return('O');
else if(user == 'X' || user == 'x') return('X');
}
The problem cause is related to the newline charachter
use scanf() in this way instead of using getchar()
scanf(" %c", &user);
It's because when you use getchar it returns the next character, but leaves the newline in the input buffer. So the next getchar returns that newline.
You should also be careful because getchar actually returns an int and not a char.
You can solve this either by another getchar, or use scanf like this:
scanf("%c ", &user);
Note the space after the c in the above format, it tells scanf to read and disregard trailing whitespace.
You could also read a line with e.g. fgets and then use a simple sscanf on that line, then no extra space is needed.
You could fix it like this for example:
char assign(void)
{
char user;
char throwaway_newline;
printf("Would you like to be X or O (Enter your choice): ");
user=getchar();
throwaway_newline = getchar();
while(user != 'X' && user != 'x' && user != 'O' && user != 'o')
{
printf("Invalid symbol, please re-enter: ");
user=getchar();
throwaway_newline = getchar();
}
if(user == 'O' || user == 'o') return('O');
else if(user == 'X' || user == 'x') return('X');
}
You have a newline in your input buffer.
When you press a character which is not [xX] and not [oO] and follow it with a newline. getchar actually gets to see 2 characters(the newline and the invalid character)
You may want to use fgets instead of relying on character input and ignoring newlines with 2 getchar() calls everytime.

Resources