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;
}

      

+3


source to share


4 answers


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 be scanf (" %c",&choice);

    to avoid the previous one newline

    .
  • scanf ("%s",&pname);

    should be scanf ("%24s",pname);

    to avoid buffer overflow.

and as mentioned in the answer by Mr. @iharob ,

  1. if (choice == 'Y');

    must be if (choice == 'Y')

    (removed ;

    ), otherwise the operator is if

    effectively useless.
  2. There is no conditional expression evaluation for else

    . However, you can use else if(choice == 'N')

    .
+8


source


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.

+6


source


Remove the half-columns.

if (choice == 'Y');  <----- remove this semicolon
 { 
     printf ("Enter %s...\n",pname);
 } 

      

The above is equivalent:

if( choice == 'Y')
  ;  /* Do nothing */
printf( ... );
else  /* syntax error, not paired with an if statement */
  ;

      

+4


source


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 
}

      

+2


source







All Articles