首页 > 解决方案 > 程序在 C 中的 if 语句之前关闭

问题描述

参数不通过if 语句,我不知道为什么。
在某些情况下,这个程序应该给你“你还有多少年?” ,考虑到您对大陆的预期寿命估计。
您输入的参数是:年龄、大陆和性别。当我执行它时,我可以输入参数,然后它就停止工作。

#include<stdio.h>

int main(){
    unsigned char gender,cont;  //cont=Continent
    char male,female,America,Oceania,Europe,Africa,Asia;
    int age,le; //le=Life expectancy
    printf("Insert Continent\n");
    scanf("%s",&cont);
    printf("Insert Gender\n");
    scanf("%s",&gender);
    printf("Insert Age\n");
    scanf("%d",&age);

    //for females
    if (gender==female) {
        if(cont==America) { 
            if(80-age<0) {
                le=80-age;
                printf("Outlived life expectancy by:\t",le);
            } else {
                le=80-age;
                printf("You are expected to live ",le," more years");
            }
        }
        if(cont==Oceania) {   
            if(80-age<0) {
                le=80-age;
                printf("Outlived life expectancy by:\t",le);
            } else {
                le=80-age;
                printf("You are expected to live ",le," more years");
            }
        }
        if(cont==Europe) {  
            if(82-age<0) {
                le=82-age;
                printf("Outlived life expectancy by:\t");
            } else {
                le=82-age;
                printf("You are expected to live ",le," more years");
            }
        }
        if(cont==Asia) {    
            if(74-age<0) {
                le=74-age;
                printf("Outlived life expectancy by:\t");
            } else {
                le=74-age;
                printf("You are expected to live ",le," more years");
            }
        }
        if(cont==Africa) {  
            if(64-age<0) {
                le=64-age;
                printf("Outlived life expectancy by:\t");
            } else {
                le=64-age;
                printf("You are expected to live ",le," more years");
                }
            }
    }
    return 0;
}

标签: c

解决方案


您将整个字符串存储在只分配了一个字符的内存中。这是“缓冲区溢出”并导致未定义的行为。

不要将它们分配为单个字符(类型char),而是尝试将它们分配为字符数组(例如,unsigned char cont[128];)。我还建议使用fgets()字符串输入,而不是使用scanf()说明%s符。

此外,不要cont == America用于比较字符串。该strcmp()功能是这项工作的正确工具。

最后,您永远不会将您在此处使用的变量定义为常量(如America)。您需要定义America(变量)(可能为"America")或cont直接与您正在测试的字符串进行比较(再次,可能"America"

int main(void) {
  const unsigned char *America="America";
  unsigned char cont[128];
  ...
  fgets(cont, 128, stdin);
  ...
  if (strcmp(cont, America) == 0) {
    ...
  }
  ...
}

推荐阅读