简体   繁体   中英

C program using structs isn't working properly

I'm attempting to create a simple program that stores ten "pets" into an array. Each stuct contains data that must be accessed through functions. For some reason this doesn't seem to be working the way I would expect. Does anyone know why the program prompts for the name and then runs through the rest of the program without prompting the user again?

#include<stdlib.h>
#include<stdio.h>
#include <string.h>

struct Pet {
    char name[50];            //name
    char type[50];            //type
    char owner[50];           //owner
};

void setPetName(struct Pet *pet, char *name){
    memcpy(pet->name,name, 50);
}

void setPetType(struct Pet *pet, char *type){
    memcpy(pet->type,type, 50);
}

void setOwner(struct Pet *pet, char *owner){
   memcpy(pet->owner,owner, 50);
}

char* getName(struct Pet *pet){
    return pet->name;
}

char* getType(struct Pet *pet){
    return pet->type;
}

char* getOwner(struct Pet *pet){
    return pet->owner;
}

void printPetInfo(struct Pet *pet){
    printf("Pet's name is %s, Pet's type is %s, Pet's owner is %s", pet->name, pet->type, pet->owner);
}

int main(){

    struct Pet Pets[9];
    int index;

    char name[50], type[50], owner[50];
    for (index=0; index<9; index++){
        struct Pet pet;
        printf("Please enter pet's name ");
        scanf("%s\n", name);
        setPetName(&pet, name);
        printf("Please enter pet's type ");
        scanf("%s\n", type);
        setPetType(&pet, type);
        printf("Please enter pet's owner ");
        scanf("%s\n", owner);
        setOwner(&pet, owner);
        printPetInfo(&pet);
        Pets[index]=pet;
   }

    return 0;
}

First you can't hold a string in a char:

char name, type, owner;

Instead you need an array of char (ie char name[50]; for example)

Then the format to scan a string is %s , not &s

scanf("&s\n", name);

And finally if you want to print a string, use format %s , not %c ( %c is to print a single char).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM