【发布时间】:2018-07-29 04:02:26
【问题描述】:
我正在开发一个 C 语言程序,该程序收集员工的数据,例如姓名、费率和工时。问题是我需要使用struct。
我正在尝试将结构数组传递给load() 函数,用户将在其中输入员工的姓名、小时数和费率,但似乎我做错了。你能告诉我有什么问题吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 3
int i = 0;
struct Employee
{
char name[20];
float rate;
float hours;
}employee;
void load(struct Employee *guys);
void printout();
void edit();
void realedit();
void print();
int main(void)
{
int x=0;
struct Employee guys[size];
while (x != 5)
{
printf("Main Menu\n");
printf("1. Add Employee\n");
printf("2. Edit Employee\n");
printf("3. Print Employee\n");
Printf("4. Print All Employees\n");
printf("5. Quit");
scanf_s("%d", &x);
switch (x)
{
case 1: load(guys[i]);
break;
default: printf("Please enter valid option.\n\n");
break;
}
}
system("pause");
return 0;
}
void load(struct Employee *guys)
{
puts("\ntype name:\n");
scanf_s("%s", &guys[i]->name, 20);
puts("\ntype hourly rate:\n");
scanf_s("%f", &guys[i]->rate);
puts("\ntype hours worked:\n");
scanf_s("%f", &guys[i]->hours);
i++;
}
【问题讨论】:
-
当您将 guy[i] 传递给 load 时,让 load retreive Employee &emp。然后只需使用 emp.name 存储数据。请注意,将“i”作为全局变量并不是一个好习惯。
-
这里
load(guys[i]);按值传递结构,但load()参数需要一个指向struct Employee的指针。 -
别忘了检查
scanf_s()调用是否成功;main()中的那个要检查确保返回1,否则有问题。 -
int i = 0;的一个全局变量只是自找麻烦。