问题
I am struggling to explain this. I need help understanding how to make a program where a user inputs information for a address and it is stored in a address book. I am using structures for three variables for the name, amount, notes but I am not sure how to save those values to the arrays in the structure. I also have to be able to access the check by the stored name.
回答1:
Your requirements are somewhat vague, but I think this may help you move towards what you're trying to accomplish. Basically, you take the code you already had and add an array called checkbook, which is filled out. You then search that checkbook for a check with a given number, and then print that check's information.
#include <stdio.h>
#define SIZE (10)
struct check {
int num;
char date[15];
char name[50];
int amt;
int val;
};
struct check get_check(void) {
struct check chk;
chk.val = 1;
printf("Enter the check number: \n");
scanf("%d", &chk.num);
fgetc(stdin);
printf("Enter the date (mm/dd/yyyy): \n");
fgets(chk.date, 15, stdin);
printf("Name of receiver: \n");
fgets(chk.name, 50, stdin);
printf("Amount: \n$");
scanf("%d", &chk.amt);
fgetc(stdin);
return chk;
}
void print_check(struct check checkbook[], int num) {
int i;
for (i = 0; i < SIZE; i++) {
if (checkbook[i].num == num && checkbook[i].val) {
printf("Num: %d\n", num);
printf("Date: %s\n", checkbook[i].date);
printf("Receiver: %s\n", checkbook[i].name);
printf("Amount: $%d\n", checkbook[i].amt);
break;
}
}
}
int main() {
int i, cnt = 0;
struct check checkbook[SIZE] = {0};
while (1) {
printf("Select an option: \n");
printf("(1) enter a new check\n");
printf("(2) find an existing check\n");
printf("(3) print all checks\n");
printf("Your selection: ");
scanf("%d", &i);
if (i == 1) {
if (cnt < SIZE) {
checkbook[cnt++] = get_check();
} else {
printf("Checkbook is full!\n\n");
}
} else if (i == 2) {
printf("Enter the desired check number: ");
scanf("%d", &i);
print_check(checkbook, i);
} else if (i == 3) {
for (i = 0; i < SIZE; i++) {
print_check(checkbook, checkbook[i].num);
}
} else {
printf("Unknown option\n\n");
}
}
return 0;
}
来源:https://stackoverflow.com/questions/60369201/how-do-i-store-user-input-from-three-different-variables-in-a-function-and-into