简体   繁体   中英

Printf, scanf & For Loop problems

My goal is to be able to input members into each struct of the array for a student database. I know my for loop is wrong somehow but I have no idea how to fix it... The output takes the first name and then prints the rest of the loop without taking the input.

Obviously the problem lies in my lack of understanding of the capabilities of printf and scanf. But just looking at it from my ignorant standpoint I don't see why it wouldn't work.

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

typedef struct {
    char *name;
    char *surname;
    char *UUN;
    char *department;
    char gender;
    int age;
} student_t;

student_t findOldest(student_t *studentarr, int len) {
    int i;
    student_t max=*(studentarr+0);

    for (i=1; i < len; i++) {
        if((*(studentarr+i)).age > max.age)
            max = *(studentarr+i);
    }

    return max;
}

int main() {
    int i;
    student_t result;
    student_t stdt[6]={{"John","Bishop","s1234","Inf",'m',18},{"Lady","Cook","s2345","Eng",'f',21},{"James","Jackson","s33456","Eng",'m',17}};
    student_t *p=&stdt[0];

    for(i=3;i<6;i++){ /* This is where I'm stuck */
        printf("\nFirst Name: ");
        scanf("%s",stdt[i].name);
        printf("\nSurname: ");
        scanf("%s",stdt[i].surname);
        printf("\nUUN: ");
        scanf("%s",stdt[i].UUN);
        printf("\nDepartment: ");
        scanf("%s",stdt[i].department);
        printf("\nGender (m/f): ");
        scanf(" %c",&stdt[i].gender);
        printf("\nAge: ");
        scanf("%d",&stdt[i].age);
    }

    findOldest(p,6);
    result = findOldest(p,6);
    printf("\nThe student of oldest age:%s, %s, %s, %s, %c, %d\n",result.name,result.surname,result.UUN,result.department,result.gender,result.age);

    return 0;
}
this compiles with no errors/warnings
it implements the desired algorithm
it greatly reduces the complexity of certain parts of the code
it give names to the magic numbers in the code
it eliminates the probability of seg fault events 
   from trying to write to pointers that points nowhere

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

#define MAX_NAME_LEN (20)
#define MAX_SURNAME_LEN (20)
#define MAX_UUN_LEN (20)
#define MAX_DEPARTMENT_LEN (20)

struct student_t
{
    char name[MAX_NAME_LEN];
    char surname[MAX_SURNAME_LEN];
    char UUN[MAX_UUN_LEN];
    char department[MAX_DEPARTMENT_LEN];
    char gender;
    int  age;
};

int findOldest(struct student_t *, int);

#define MAX_STUDENTS (6)

int main()
{
    int i; // loop counter
    int result; // returned index from findOldest()
    struct student_t stdt[MAX_STUDENTS]=
    {
        {"John","Bishop","s1234","Inf",'m',18},
        {"Lady","Cook","s2345","Eng",'f',21},
        {"James","Jackson","s33456","Eng",'m',17}
    };


    // enter info for last 3 students
    for( i=3; i<6; i++ )
    {
        printf("\nEnter First Name: ");
        if( 1 != scanf(" %s", stdt[i].name) )
        { // then, scanf failed
            perror( "scanf failed for name" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf for name successful

        printf("\nEnter Surname: ");
        if( 1 != scanf(" %s", stdt[i].surname) )
        { // then scanf failed
            perror( "scanf failed for surname" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf for surname successful

        printf("\nEnter UUN: ");
        if( 1 != scanf(" %s", stdt[i].UUN) )
        { // then scanf failed
            perror( "scanf failed for UUN" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf for UUN successful

        printf("\nEnter Department: ");
        if( 1 != scanf(" %s",stdt[i].department) )
        { // then scanf failed
            perror( "scanf failed for department" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf for department successful

        printf("\nEnter Gender (m/f): ");
        if( 1 != scanf(" %c", &stdt[i].gender) )
        { // then scanf failed
            perror( "scanf failed for gender" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf for gender successful

        printf("\nEnter Age: ");
        if( 1 != scanf(" %d", &stdt[i].age) )
        { // then scanf failed
            perror( "scanf failed for age" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf for age successful

    } // end for


    result = findOldest( stdt, MAX_STUDENTS );
    printf("\nThe student of oldest age:%s, %s, %s, %s, %c, %d\n",
        stdt[result].name,
        stdt[result].surname,
        stdt[result].UUN,
        stdt[result].department,
        stdt[result].gender,
        stdt[result].age);

    return 0;
} // end function: main

// note: if more than one student has same (oldest) age
//       then the student index of the first student
//       of that age will be returned
int findOldest(struct student_t *studentarr, int len)
{
    int i; // loop index
    int max   = -1;
    int index = -1;

    for (i=0; i < len; i++)
    {
        if( studentarr[i].age > max )
        {
            max = studentarr[i].age;
            index = i;
        } // end if
    } // end for

    return index;
} // end function findOldest

You're trying to write data to non-allocated space. Change your struct to use char[]:

typedef struct {
    char name[200];
    char surname[200];
    char UUN[200];
    char department[200];
    char gender;
    int age;
} student_t;

(200 here is just an example; adjust for your needs)

If you really want to keep them as char* you can:

i) allocate each one beforehand with malloc :

    ...
    printf("\nFirst Name: ");
    stdt[i].name = malloc(200);
    scanf("%s",stdt[i].name);
    ...

or

ii) scanf to a buffer, then copy the result to the final member:

int main() {
    ...
    char buffer[200];

    for(i=3;i<6;i++){ /* This is where I'm stuck */
        printf("\nFirst Name: ");
        scanf("%s",buffer);
        stdt[i].name = strdup(buffer);
    ...

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