【发布时间】:2014-11-29 01:09:27
【问题描述】:
我目前正在开发一个将龙添加到用户团队的程序。要添加通过文件扫描的龙。为了添加它们,我知道我必须使用至少一个 2D 数组。有人可以告诉我我的程序设置是否正确吗?当谈到用 C 编程时,我对结构和函数的经验很少,因此我不知道我是否正确设置了我的项目。
代码:
//included libraries
#include <stdio.h>
#include <string.h>
//constants
#define MAX_LENGTH 40
#define MAX_TEAM 1000
//function prototypes
int add_dragon(char name, char color, int num_dragons, int Dragon_array);
//structures
struct dragon {
char name[MAX_LENGTH];
char color[MAX_LENGTH];
};
struct collection {
struct dragon team[MAX_TEAM];
int num_dragons;
};
//main function
int main() {
//list variables in main function
int i, j, num_dragons, choice = 0;
//set up file
FILE * ifp = fopen("dragon.txt", "r");
//check to see if there is a file
if(ifp == NULL){
printf("Error! No file can be found!");
return 1;
}
printf("Welcome! You are about to start collecting dragons!\n");
//while loop for repeating the menu
while(num_dragons < MAX_TEAM){
printf("What would you like to do to your team of dragons?\n\n");
printf("\t 1- Add to team\n");
printf("\t 2- Remove from team\n");
printf("\t 3- Search for dragon on team\n");
printf("\t 4- List dragons\n");
scanf("%d", & choice);//enter choice
//conditions to prompt for a valid choice
while(choice > 4)
scanf("%d", &choice);
while(choice < 1)
scanf("%d", &choice);
//enter dragon name and color
fscanf(ifp, "%s", &num_dragons);
}
return 0;
}
//Pre_condition: choivr us set to zero
//Post_condition allows user to select a choice
//Preconditions: menu is set up and variables are declared
//postConditions: will allow user to add a dragon to their team
int add_dragon(char name, char color, int num_dragons, int Dragon_array){
//variables
int i, j;
//if(num_dragons < MAX_TEAM)//check if numer of dragons doesn't exceed max size of the team{
Dragon_array [MAX_TEAM] [MAX_TEAM];
for(i = 0; i < MAX_TEAM; i ++)
for(j = 0; j < MAX_TEAM; j ++){
num_dragons ++;
}
printf("%s the %s dragon has been added to the team\n", name, color);// confirm that the dragon was added to team
return num_dragons;
}
【问题讨论】:
-
您的代码中有太多错误。我建议您从教科书或在线教程开始学习语言。 C教材:amazon.com/dp/0131103628/?tag=stackoverfl08-20。在线教程:tutorialspoint.com/cprogramming/index.htm.
标签: c file function struct structure