如果声明不工作立即结束程序

时间:2014-02-11 23:36:15

标签: c if-statement

我正在制作一个天气人员代码但是当我要求温度时它会结束程序。这是代码。

#include <stdio.h>
int main(void)
{
    int a;
    int b;
    int c;
    int d;
    printf("What Is Your Name?\n");
    scanf("%s",&b);
    printf("Hi %s\n", &b);
    sleep(1);
    printf("Im Your Own Weather Man\n");
    sleep(1);
    printf("Isn't That Great!\n");
    sleep(1);
    printf("Please Type A Number In\n");
    sleep(1);
    scanf("%d",&a);
    //checking out the number you wrote
    if(a<3)
    {
        printf("Its A Beatiful Day\n");
        printf("%c\n",2);
    }
    if(a>3)
    {
        printf(":(\n");
    }
    if(a==3)
    {
        printf("Its Snowing!\n");
        printf("%c\n",3);
        sleep(5);
        printf("Would you like to know the temprature?\n");
        scanf("%s", &c);
    }
    if(c=='yes')

        printf("20F\n");

    return 0;

}

我认为它搞乱了(c =='是')
我怎么能打印出20 F?

[编辑]感谢您帮助我将新代码放在下面,随时可以随意使用,但是可以归功于我。

#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
int a,b;
char c[5];
char d[30];
printf("What Is Your Name?\n");
scanf("%s",d);
printf("Hi %s\n", d);
sleep(1);
printf("Im Your Own Weather Man\n");
sleep(1);
printf("Isn't That Great!\n");
sleep(1);
printf("Please Type A Number In\n");
scanf("%d",&a);
//checking out the number you wrote
if(a<3)
{
    printf("Its A Beatiful Day\n");
    printf("%c\n",2);
}
if(a>3)
{
    printf("Its A Cloudy Day");
    printf(":(\n");
}
if(a==3)
{
    printf("Its Snowing!\n");
    printf("%c\n",3);
    sleep(5);
    printf("Would you like to know the temprature?\n");
    scanf("%s",c);
}

    if(strcmp("yes", c) == 0)
    printf("20F\n");

   return 0;

}

3 个答案:

答案 0 :(得分:3)

问题在于您使用以下行将字符串读入int:

scanf("%s", &c);

尝试这样做,%d显示输入的类型为int。

scanf("%d", &c);

答案 1 :(得分:3)

c被定义为int,但您将其视为char*

您还应该使用strcmp代替==。您无法将字符串与==运算符进行比较。

c的定义更改为:char c[128]或其他任意长度。然后在执行scanf时删除&运算符:scanf("%s", c);最后,将if (c=='yes')更改为if (strcmp("yes", c) == 0)

答案 2 :(得分:1)

 if(c=='yes')

        printf("20F\n");

您无法执行此操作,因为'yes'是错误声明的character constant,即使它是string literal "yes",您也无法直接在c中比较字符串。使用内置库函数或编写自己的函数进行字符串比较/