Fixing those if, else statements
Problems seem to be on
Line 18: warning: comparison between pointer and integer line 22: error: expected expression before 'else'
What am I doing wrong? Is there a better way to do this?
#include <stdio.h>
int main(void)
{
char pname[25];
char Y[1];
char N[1];
char choice[1];
printf("when responding to Yes or No questions use Y/N.\n");
printf("Hello,traveler Welcome to the Castle of Atal...."
"What is your name?\n");
scanf("%s", &pname);
printf("Greeting %s What bring you to the kingdom of Tharnos?\n",
pname);
printf("I see how intresting do you wish to enter %s ?\n", pname);
scanf("%c", &choice);
if (choice == 'Y');
printf("Enter %s...\n", pname);
else (choice == 'N');
printf("Farewell lost soul!\n");
return 0;
}
source to share
In your code, change the definitions
char Y [1];
char N [1];
char choice[1];
to
char Y;
char N;
char choice;
Otherwise, with the current definition choice
represents array
(of 1 element) which
- not required here, one
char
will work fine. - throws a warning to execute
choice == 'Y'
because you cannot compare an array to an operator==
.
Nevertheless,
-
scanf ("%c",&choice);
should bescanf (" %c",&choice);
to avoid the previous onenewline
. -
scanf ("%s",&pname);
should bescanf ("%24s",pname);
to avoid buffer overflow.
and as mentioned in the answer by Mr. @iharob ,
-
if (choice == 'Y');
must beif (choice == 'Y')
(removed;
), otherwise the operator isif
effectively useless. - There is no conditional expression evaluation for
else
. However, you can useelse if(choice == 'N')
.
source to share
Your if statement has problems
-
You shouldn't put a semicolon at the end of an if statement, which would mean an if statement with an empty block of code.
-
Syntax
else (choice == 'N');
incorrect, there is an equivalent though
else if (choice == 'N'); /* ^ you should add `if' after `else' */
Your code has more problems, but you didn't ask about them. @ SouravGhosh reached out to them anyway.
source to share
Your syntax is incorrect, you must use the correct syntax:
if (condition) {
} else if (condition) {
}
or you can use this if you have something default when none of your conditions are true:
if (condition) {
} else if (condition) {
} else {
// you will get in this if when all of your conditions become false
}
source to share