修复这个if,else语句
问题似乎正在发生
第18行:警告:指针和整数之间的比较
第22行:错误:’else’之前的预期表达式
我究竟做错了什么? 有更好的方法吗?
#include 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; }
在您的代码中,更改定义
char Y [1]; char N [1]; char choice[1];
至
char Y; char N; char choice;
否则,使用当前定义, choice
表示一个array
(1个元素),其中
- 这里不需要,一个
char
就可以了。 - 会触发
choice == 'Y'
的警告,因为你不能将数组与==
运算符进行比较。
那说,
-
scanf ("%c",&choice);
应该是scanf (" %c",&choice);
避免以前的newline
。 -
scanf ("%s",&pname);
应该是scanf ("%24s",pname);
避免缓冲区溢出。
并且,如@iharob先生的回答 所述 ,
-
if (choice == 'Y');
应该是if (choice == 'Y')
(删除),否则,if
语句实际上是无用的。 - 其他没有条件表达式评估 。 但是,你可以使用
else if(choice == 'N')
。
您的if语句确实存在问题
-
你不应该在if语句的末尾加一个分号,这意味着一个带有空代码块的if语句。
-
语法
else (choice == 'N');
是错的,虽然有一个等价物
else if (choice == 'N'); /* ^ you should add `if' after `else' */
您的代码有更多问题,但您没有询问它们。 无论如何,@ SouravGhosh确实解决了这个问题。
删除分号。
if (choice == 'Y'); <----- remove this semicolon { printf ("Enter %s...\n",pname); }
以上相当于:
if( choice == 'Y') ; /* Do nothing */ printf( ... ); else /* syntax error, not paired with an if statement */ ;
你的语法不正确,你应该使用正确的语法:
if (condition) { } else if (condition) { }
或者你可以使用这个,如果你有任何默认的事情,当你的条件都没有时:
if (condition) { } else if (condition) { } else { // you will get in this if when all of your conditions become false }