Home > Net >  Reading strings to an array
Reading strings to an array

Time:11-04

Im doing a practice execise for my Coding class and Cant for the love of me figure out how to Fix it, The strings work within the loop but for some reason I cant read them to an array so I can pull them back to work with them later.

Ive been having troubles grabbing my strings that im making in the first loop in main, and it has been killing me cause ive tried multiple different solutions with none working

Here is the code ive currently writen

#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 %s\n", 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

CodePudding user response:

In these calls, the array type decays into a pointer to the first Animal in the array:

getAnimal(type);
visitAnimal(type);

In order to supply a pointer to the i:th Animal:

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

CodePudding user response:

you are passing the same struct into getAnimal each time

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

you need instead

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