int main (void)
{
char tttarray[3][3] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
int turn = 0,i,j,loc;
char XO;
while(turn<=9)
{
printf("Enter (x) or (o): ");
scanf("%c",&XO);
getchar();
printf("Enter number: ");
scanf("%d", &loc);
j = (loc - 1)%3;
i = (loc - 1)/3;
if(tttarray[i][j] == 'x' || 'o')
{
return(0);
printf("That spot has been taken!\n");
}
tttarray[i][j] = XO;
printArray(tttarray);
}
}
I'm only showing main the code for convenience. My problem is with this part:
if(tttarray[i][j] == 'x' || 'o')
{
return(0);
printf("That spot has been taken!\n");
}
This is because it always seems to be true which prevents the player from placing an 'x' or 'o' there. Am I missing something in the above code? How do prevent the user from going to a taken space?
You cannot chain the logical OR operator like you did. You need to change
if(tttarray[i][j] == 'x' || 'o')
to
if((tttarray[i][j] == 'x') || (tttarray[i][j] =='o'))
That said, a statement after a return statement does not make any sense. Control will never reach the printf() inside the if condition. Maybe what you want is to use
printf() statement
continue;
in this very order.
Related
I'm trying to do loop menu with some basic functions, everything is working fine apart of looping menu
in my opinion i have something wrong with while loop but i can't figure out what it is.
int main(void) {
char letter;
char status = 0;
printf ("--------------------------------------\n");
printf("a – Calculate the area of a rectangle\n");
printf("b – Calculate the area of a circle\n");
printf("c – Display a multiplication table\n");
printf("d – Add two numbers\n");
printf("x - exit program\n");
printf ("--------------------------------------\n");
scanf("%c",&letter);
while (status == 0)
{
if (letter == 'a' || letter == 'A')
{
}
if (letter == 'b'|| letter == 'B')
{
}
if(letter == 'c'|| letter == 'C')
{
}
if (letter == 'd'|| letter == 'D')
{
}
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
break;
}
status ++
}
return 0;
}
You need to pace a scanf(" %c",&letter); inside the loop body; otherwise, you will not get a chance to ever enter an x...
Please note the space before the %c, i.e. the " %c"-format, which captures any new line in the input buffer from a previous input.
Maybe you meant that status will be int and not char?
You should read input also in the beginning of loop, otherwise you will take only one input
After the first iteration, you advance status so it will exit the loop. Is this what you tried to achieve? I guess you meant for:
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
status ++
break;
}
Your loop will run only one time cause 'status ++' will work no matter the condition you should use it inside the x case -
if(letter == 'x' || letter == 'X')
{
printf("shut down\n");
status ++;
}
This should break your loop only after 'x' is entered.
I am working on an assignment in C, trying to create a program that simulates a "Rock, Paper, Scissors" match between the user and the computer. Everything is working fine except the for loop I have created is skipping the first iteration of the loop and going straight to my second match. Is there any way to fix this? Code and compilation below
main.c
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main(void) {
srand(time(0)); // This gives the random function a new seedallows me to use time in order to create "random" numbers. //
time_t t; // Allows the program to store system time values. //
int R; // This statement declares the variable for the move "Rock". //
int P; // This statement declares the variable for the move "Paper". //
int S; // This statement declares the variable for the move "Scissors". //
int numMatches; // This statement declares the variable for the number of matches that are to be played. //
int roundNumber; // This statement declares the variable for the current round of the match that is being played. //
int compMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the computer makes. //
char userMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the user of the program chooses. //
int randNumber; // This statement declares the variable for the random number that will be generated. //
printf("Starting the Rock, Paper, Scissors Game!\n");
printf("Enter the number of matches to play: ");
scanf(" %d", &numMatches); // This statement allows the user to input the number of matches he/she wishes to play. //
for (roundNumber = 1; roundNumber <= numMatches; roundNumber++) { // This for statement first initializes the number of rounds to 1. Then, the statement sets a parameter that the for loop will only continue as long as the number of matches completed is less that than the total matches that are to played. The last statement increments
printf("\nMatch %d: Enter R for rock, P for paper, or S for scissors: ", roundNumber);
fflush(stdin);
userMove = getchar();
randNumber = (rand() % 3) + 1; //1 to 3//
compMove = randNumber == 0 ? 'R' : randNumber == 1 ? 'P' : 'S';
if ((userMove == 'R') && (compMove == 'S')) { // These statements state the result of the game depending on the user's move and the computer's move. //
printf("The computer chose scissors. You won \n");
} else
if ((userMove == 'P') && (compMove == 'R')) {
printf("The computer chose rock. You won \n");
} else
if ((userMove == 'S') && (compMove == 'P')) {
printf("The computer chose paper. You won \n");
} else
if ((userMove == 'R') && (compMove == 'R')) {
printf("The computer chose rock. You tied \n");
} else
if ((userMove == 'P') && (compMove == 'P')) {
printf("The computer chose paper. You tied \n");
} else
if ((userMove == 'S') && (compMove == 'S')) {
printf("The computer chose scissors. You tied \n");
} else
if ((userMove == 'R') && (compMove == 'P')) {
printf("The computer chose paper. You lose \n");
} else
if ((userMove == 'P') && (compMove == 'S')) {
printf("The computer chose scissors. You lose \n");
} else
if ((userMove == 'S') && (compMove == 'R')) {
printf("The computer chose rock. You lose \n");
}
}
return 0;
}
compile
The line:
userMove = getchar();
Catches the char but lets a newline character \n in the buffer caused by pressing Enter, you need to discard it.
You can do, for instance, this:
userMove = getchar();
getchar(); // <-- catches and discards '\n'
I would also get rid of fflush(stdin), it causes undefined behaviour, reasons in Why should I use fflush(stdin) in this program?.
Replace it also with getchar(). Or use type specifier with discard in your scanf function like scanf(" %d%*c", &numMatches);
Here is a working sample
Another thing that is not very good is the fact that none these variables is being used:
time_t t; // Allows the program to store system time values. //
int R; // This statement declares the variable for the move "Rock". //
int P; // This statement declares the variable for the move "Paper". //
int S; // This statement declares the variable for the move "Scissors". //
I'm facing a problem with what I enter with any unknown during the first time to the program. it will show me an infinite loop problem program closing. The program won't read the else statement.
char cont;
printf("Do u want continue\n");
scanf("%c", &cont);
getchar();
do
{
if (cont == 'y' || cont == 'Y')
{
selection();
}
else if (cont != 'n' || cont != 'N')
{
printf("Program Closing \n");
}
else
{
printf("Invalid Please Re-enter");
getchar();
scanf("%c", &cont);
}
} while (cont != 'n'&& cont != 'N');
let's dissect your code line by line starting with
scanf("%c", &cont);
This line would get a char value from stdin and put it into cont, which is a char so that's fine
getchar();
All I have to say for this is, why? it doesn't do anything useful, remove it.
Entering the loop now we have this statement
if (cont == 'y' || cont == 'Y')
this line is correct, it checks if the character is equal to y or Y
else if (cont != 'n' || cont != 'N')
this line is the main issue, your statement checks if cont is a value NOT equal to n or N, i.e. as a comment mentioned above, if the user put in the value a this line would return true, and then end the program. To correctly check if the user wants to exist you can use the same if statement used for y
if (cont == 'n' || cont == 'N')
if you replace the original if statement with this your program should work as expected. Just remember in the future that the != means not equal to, i.e. if the value is anything besides n or N return true. The == operator checks for equality as you saw above, so the line cont == 'n' means return true if cont is the same value as 'n'
printf("Invalid Please Re-enter");
getchar();
scanf("%c", &cont);
also as an extra note, please explain why you keep throwing in useless getchar()'s, those lines literally do nothing and you should remove them.
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);
}
}
}
typedef struct contact {
char firstname [40];
char lastname [40];
char address [100];
char phone[10];
}contact;
int main ()
{
FILE *pFile;
contact entry = {"", "", "", ""};
int choice;
char cont = 5;
pFile = fopen("C:\\contacts.txt", "w+");
if(!pFile){
printf("File could not be open");
return 1;
}
printf("Choose a selection\n\n");
printf("1. Enter First Name\n");
printf("2. Enter Last Name\n");
printf("3. Enter Address\n");
printf("4. Enter Phone Number\n\n");
scanf( "%d", &choice);
while (choice = 1|2|3|4|cont){
if (choice = 1){
printf ("First name: ");
fgets(entry.firstname, sizeof(entry.firstname),stdin);
}
else if(choice = 2){
printf ("Last name: ");
fgets(entry.lastname, sizeof(entry.lastname),stdin);
}
else if(choice = 3){
printf ("Address: ");
fgets(entry.address, sizeof(entry.address),stdin);
}
else if (choice = 4){
printf ("Phone number: ");
fgets(entry.phone, sizeof(entry.phone),stdin);
}
else
printf("Exiting");
break;
fwrite (&entry, sizeof (struct contact), 1, pFile);
printf ("Would you like to enter a new contact? (y/n)");
scanf ("%d", &cont);
if (cont = 'n'|'N')
return 0;
}
fclose(pFile);
getchar();
return 0;
}
is my code at the moment. Each time I give any option 1,2,3,4, put in a entry and press enter the window closes. I'm unsure if the logic makes sense and any suggestions are welcome but it "seems" okay to me but obviously I need another set of eyes. I want it where I don't have to enter all entries for every person I put in the file. Also, to note, I initially cont to 5 just because it was complaining.. bad practice I know. Any helpful information is appreciated
Your program ends because the break; isn't in the scope you think it is:
else if (choice = 4){
printf ("Phone number: ");
fgets(entry.phone, sizeof(entry.phone),stdin);
}
else
printf("Exiting");
break;
Even though you've indented the break, it doesn't belong to the else clause. So no matter what happens in the if/else block, the break gets executed and your program breaks out of the loop and ends.
To fix it, add braces to enclose the break inside the scope of the else.:
else if (choice = 4){
printf ("Phone number: ");
fgets(entry.phone, sizeof(entry.phone),stdin);
}
else
{
printf("Exiting");
break;
}
And once you fix that, this line will cause your program to terminate because it always evaluates to true and returns from main:
if (cont = 'n'|'N')
return 0;
You want that line to say
if (cont == 'n' || cont == 'N')
return 0;
These fixes will at least stop your program from terminating, but as others have pointed out there are numerous logical errors elsewhere that will prevent it from doing what you want.
For example, the following line:
while (choice = 1|2|3|4|cont){
belies a misunderstanding of some fundamental concepts.
First = is the assignment operator. The above code, among other things, changes the value of choice. Use == for equality comparison.
Second, the | operator is a bitwise or. The value of 1|2|3|4|5 is 7 (I'll leave it to you to figure out why sometime). Instead, use || like this:
while (choice == 1 || choice == 2 || choice == 3 || choice == 4 || choice == cont) {
There are other similar errors throughout your code.
A single = does assignment in C. if (a = 5) { /* always executed! */ } sets a to 5 and then executes the if-branch because a = 5 evaluates to 5 which is considered true.
You want == which compares values. Thus:
if (choice = 1){
Should be
if (choice == 1){
Another thing:
while (choice = 1|2|3|4|cont){
Does not do what you think it does. It's actually computing the bitwise or of 1, 2, 3, 4 and cont. (So just changing = to == wouldn't be sufficient.) You need to compare each value in turn:
while (choice == 1 || choice == 2 || choice == 3 || choice == 4 || choice == cont){
Also notice the use of || (logical OR) instead of bitwise or.
EDIT: The reason your program prematurely exits is because of the following:
else
printf("Exiting");
break;
You're missing curly braces ({ and }), so it actually means the following (despite misleading indention):
else
printf("Exiting");
break;
Your code probably has more errors.
By using if (choice = 1) you are saying "If I change choice to 1" which is virtually guaranteed to work, but it destroys the previous value choice held.
You want to start off with if (choice == 1) which means "If I compare choice to 2, is this equal?`.