NameNotFound
NameNotFound

Reputation: 15

When printing array of structs, getting ascii symbols and no names or values

I am not sure if this issue is born from my input of info into the struct, or my printing routine.

My code looks like this:

struct srecord {
        char name[15];
        int score;
};
void getAScore(struct srecord r, char name[], int scores){
                strcpy(r.name,name);
                r.score = scores;
}                                                                                                   
void getScores(struct srecord students[], int* num ){
        printf("Enter number of students and then those students names and scores separated by a space.\n");
        scanf("%d", num);
        int i;
        char names[15];
        int scores;
        int j;
        for(i = 0; i < *num; i++){
                scanf("%s%d", names, &scores);
                getAScore(students[i], names, scores);

        }
}

void printAScore(struct srecord r){
        printf("%s%d\n", r.name, r.score );
}
void printScores(struct srecord r[],int num){
        int i;
        for(i = 0; i < num; i++){
                printAScore(r[i]);
        }
}

As you can see the struct is comprised of a name array, and score. We create 10 of these structs in an array in the main class.

int main(){
        struct srecord students[10]; // can handle up to 10 records
        int num; // number of students
        int average;
        getScores(students, &num);
        printScores(students, num);

I have to input all of the info at once in the terminal, and then print it out exactly the same.

So I put an input like this, where the first line is the number of students, and each subsequent line is a name followed by a score, like so:

3
Tom 90
Jones 78
lawrence 8

However, when I go to print it I get this:

@0
0
0

I believe my pointers are correct, but I assume that the info is being put incorrectly into the array of structs? I've been fooling around with the loops, but nothing important has changed, and nothing is really working, so I am just sort of lost with this right now. I looked up the manual for structs and printf and scanf, but nothing really stuck out to me as to what may be the issue, nor have other threads on the topic.

Upvotes: 0

Views: 201

Answers (1)

Barmar
Barmar

Reputation: 780879

getAScore() needs to receive a pointer to the structure so it can modify it. Otherwise it's modifying a local copy that goes away when the function returns.

It also needs to copy the name into the structure.

void getAScore(struct srecord *r, char name[], int scores){                                                                                                                   strcpy(r.name,name);
    r->score = scores;
    strcpy(r->name, name);
}

Then change the call to:

getAScore(&students[i], names, scores);

Upvotes: 1

Related Questions