源文件(主函数)
#include <stdlib.h>
#include <stdio.h>
#include "xx.h"
extern Hero heros[100];
int main()
{
Input();
ShowHero();
//InputHero();
}
一个源文件的内容
#include <stdlib.h>
#include <stdio.h>
#include "xx.h"
Hero heros[100] = { //给他留够足够的空间
{1,"hah","m","刺客",579,1.5,"啊啊",{2002,01,11}},
{2,"aa","m","法师",1000,3.5,"啊啊",{2001,04,15}},
//不可以使用单引号!!!
};
int count = 2; //当前的英雄总数
//也可以使用 int len =sizeof(heros)/sizeof(Hero)
Job jobs[] = {
{1,"法师","安琪拉"},
{2,"刺客","李白"},
{3,"战士","亚瑟"},
{4,"射手","虞姬"},
{5,"辅助","蔡文姬"}
};
void Input()
{
//首先录入内容
//第一个录入完毕后,询问是否继续录入 do-while结构
char answer = 'y';
do {
if (count == 100)
{
printf("库存英雄已满 请到商城购买");
}
printf("\n----------------当前录入第%d位英雄的信息----------------\n", count + 1);
printf("英雄的名称是:");
heros[count].name = (char*)malloc(50);
scanf("%s", heros[count].name);
fflush(stdin);
printf("\n性别是:");
fflush(stdin);
scanf("%s", &heros[count].sex);
printf("\n职业是:");
fflush(stdin);
heros[count].job = (char*)malloc(50);
scanf("%s", &heros[count].job);
heros[count].hp = 1000;
printf("\n血量为:%.2f", heros[count].hp);
heros[count].speed = 0.77;
printf("\n速度为:%.2f", heros[count].speed);
//heros[count].ability = "上天,入地"; char *ability; 是一个char型数组 字符指针,可以直接指向一个字符串常量
printf("\n特殊能力为:");
heros[count].name = (char*)malloc(50);
scanf("%s", heros[count].name);
fflush(stdin);
heros[count].pubtime.year = 2016;
heros[count].pubtime.month = 04;
heros[count].pubtime.day = 28;
printf("\n上线时间为%d年%d月%d日",
heros[count].pubtime.year, heros[count].pubtime.month, heros[count].pubtime.day);
count++;//每次录入完成后 英雄总数加1
printf("\n是否继续录入?(y/n)");
//scanf("%s", &answer);//也可以用getch()
//getchar()用户按下键后立即触发下面语句 不会再让用户敲回车
scanf("%s", &answer);
} while (answer == 'y' || answer == 'Y');
}
void ShowHero()
{
int i;
printf("\n");
for (i = 0; i < count; i++)
{
printf("%s\t%s\t%d-%d-%d\n", (heros + i)->name, heros[i].job, heros[i].pubtime.year, heros[i].pubtime.month, heros[i].pubtime.day);
}
}
头文件的内容
#ifndef XX_H_INCLUDED
#define XX_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#pragma once
//1- 结构体: 英雄 职业 能力 时间
typedef struct _job //typrdef 宏定义一个类型 (和define差不多) 简化结构体的使用 Job.job
{
int id;
char* name;
char* desc; //职业描述
}Job;
typedef struct _ability
{
int id;
char* name;//特殊能力名称
char* intro; //特殊能力说明
}Ability;
typedef struct _pubTime
{
int year;
int month;
int day;
}PubTime;
typedef struct _hero
{
int id;
char* name; //英雄 名称
char* sex;
char * job; //英雄的职业
double hp; //生命值
double speed; //攻击速度
char *ability; //特殊能力
PubTime pubtime; //上线时间
}Hero;
//用来输入英雄的值
//动态录入代码
void InputHero();
void Input();
//用来输出英雄的值
void ShowHero();
#endif //XX_H_INCLUDED
我的问题:printf("\n是否继续录入?(y/n)");
//scanf("%s", &answer);//也可以用getch()
//getchar()用户按下键后立即触发下面语句 不会再让用户敲回车
scanf("%s", &answer);
} while (answer == 'y' || answer == 'Y');
到这个语句的时候 scanf如果输入y可以继续执行,可是一旦输入了n就会报错。
如果把scanf换成getchar 没有输入的过程 直接跳到了ShowHero()函数。