c语言 - 将字符串读取到数组



我正在为我的编码课做练习,并且不能为我的爱弄清楚如何修复它,字符串在循环中工作,但由于某种原因我无法将它们读取到数组中,以便我可以将它们拉回以后使用它们。

我一直在抓住我在 main 的第一个循环中制作的字符串时遇到麻烦,它一直在杀死我,因为我尝试了多种不同的解决方案,但没有一个有效

这是我当前编写的代码

#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 10
typedef struct {
char name[MAX_LEN];
char food[MAX_LEN];
char sound[MAX_LEN];
} Animal;
/*Takes a pointer to an Animal struct and returns nothing*/
void getAnimal(Animal* type);
/*Takes a pointer to an Animal and returns nothing*/
void visitAnimal(Animal* type);
int main() {
int i = 0;
int count = 0;
Animal type[MAX_LEN] = {};
printf("How many Animals Are there on the farm?: ");
scanf("%d", &count);
for (i = 0; i < count; ++i) {
getAnimal(type);
}
printf("Welcome to our farm.n");
for (i = 0; i < count; ++i) {
visitAnimal(type);
}
return 0;
}
/**/
void getAnimal(Animal* type) {
printf("Enter the name of the animal: ");
scanf("%s", type->name);
printf("What does a %s eat?: ", type->name);
scanf("%s", type->food);
printf("Enter the sound made by a %s: ", type->name);
scanf("%s", type->sound);
}
/**/
void visitAnimal(Animal* type) {
printf("This is a %s. It eats %s and says %sn", type->name, type->food,
type->sound);
}
sh-4.2$ gcc -ansi -Wall PE10.c
sh-4.2$ a.out
How many Animals Are there on the farm?: 2
Enter the name of the animal: cow 
What does a cow eat?: wheat
Enter the sound made by a cow: moo
Enter the name of the animal: Duck 
What does a Duck eat?: seeds
Enter the sound made by a Duck: quack
Welcome to our farm.
This is a Duck. It eats seeds and says quack
This is a Duck. It eats seeds and says quack

每次都把相同的结构传递给getAnimal

for (i = 0; i < count; ++i) {
getAnimal(type);
}

你需要代替

for (i = 0; i < count; ++i) {
getAnimal(&type[i]);
}

在这些调用中,数组type衰减为指向数组中第一个Animal的指针:

getAnimal(type);
visitAnimal(type);

为了提供指向i的指针:thAnimal

getAnimal(type + i);   // or getAnimal(&type[i]);
visitAnimal(type + i); // or visitAnimal(&type[i]);

最新更新