修复此 if,else 语句 [英] Fixing this if,else statements

查看:15
本文介绍了修复此 if,else 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题似乎出在

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

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 of doing 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.
");
    printf("Hello,traveler Welcome to the Castle of Atal...."
            "What is your name?
");
    scanf("%s", &pname);

    printf("Greeting's %s What bring's you to the kingdom of Tharnos?
",
            pname);
    printf("I see how intresting do you wish to enter %s ?
", pname);
    scanf("%c", &choice);

    if (choice == 'Y');
        printf("Enter %s...
", pname);
    else (choice == 'N');
        printf("Farewell lost soul!
");

    return 0;
}

推荐答案

在您的代码中,更改定义

In your code, change the definitions

char Y [1];
char N [1];
char choice[1];

 char Y;
 char N;
 char choice;

否则,在当前定义下,choice 表示一个 array(1 个元素),其中

Otherwise, with the current definition, choice represents an array (of 1 element), which

  • 这里不需要,单个 char 就可以了.
  • 将触发执行 choice == 'Y' 的警告,因为您无法将数组与 == 运算符进行比较.
  • is not required here, a single char will work just fine.
  • will trigger the warning for doing choice == 'Y', because, you cannot compare array with == operator.

也就是说,

  1. scanf("%c",&choice); 应该是 scanf("%c",&choice); 以避免前面的 换行.
  2. scanf ("%s",&pname); 应为 scanf ("%24s",pname); 以避免缓冲区溢出.
  1. scanf ("%c",&choice); should be scanf (" %c",&choice); to avoid the previous newline.
  2. scanf ("%s",&pname); should be scanf ("%24s",pname); to avoid buffer overrun.

并且,正如 @iharob 先生 在回答中提到的,

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

  1. if (choice == 'Y');应该是 if (choice == 'Y')(把 ; 去掉),否则,if 语句实际上是无用的.
  2. else 没有条件表达式评估.不过,您可以使用 else if(choice == 'N').
  1. if (choice == 'Y');should be if (choice == 'Y') (the ; removed), otherwise, the if statement is effectively useless.
  2. There is no conditional expression evaluation for else. You can make use of else if(choice == 'N'), though.

这篇关于修复此 if,else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆