修复这个if,else语句

Dea*_*ng0 3 c char

问题似乎正在发生

第18行:警告:指针和整数之间的比较
第22行:错误:'else'之前的预期表达式

我究竟做错了什么?有没有更好的方法呢?

#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 %s What bring's 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;
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 8

在您的代码中,更改定义

char Y [1];
char N [1];
char choice[1];
Run Code Online (Sandbox Code Playgroud)

 char Y;
 char N;
 char choice;
Run Code Online (Sandbox Code Playgroud)

否则,使用当前定义,choice表示array(1个元素),其中

  • 在这里不需要,单个char将工作得很好.
  • 会触发警告choice == 'Y',因为,你无法将数组与==运算符进行比较.

那说,

  1. scanf ("%c",&choice);应该scanf (" %c",&choice);避免以前的newline.
  2. scanf ("%s",&pname);scanf ("%24s",pname);避免缓冲区溢出.

并且,如@iharob先生的回答所述,

  1. if (choice == 'Y');应该if (choice == 'Y')(被;删除),否则,该if陈述实际上是无用的.
  2. 没有条件表达式求值else.但是你可以利用else if(choice == 'N')它.


Iha*_*imi 6

您的if语句确实存在问题

  1. 你不应该在if语句的末尾加一个分号,这意味着一个带有空代码块的if语句.

  2. 语法

    else (choice == 'N');
    
    Run Code Online (Sandbox Code Playgroud)

    是错的,虽然有一个等价物

    else if (choice == 'N');
    /*   ^ you should add `if' after `else' */
    
    Run Code Online (Sandbox Code Playgroud)

您的代码有更多问题,但您没有询问它们.无论如何,@ SouravGhosh确实解决了这个问题.