简体   繁体   English

Printf,scanf和For Loop问题

[英]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. 我知道我的for循环某种程度上是错误的,但是我不知道如何解决它...输出使用名字,然后在不使用输入的情况下打印循环的其余部分。

Obviously the problem lies in my lack of understanding of the capabilities of printf and scanf. 显然,问题出在我缺乏对printf和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[]: 更改您的结构以使用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) (这里仅提供200个示例;根据您的需要进行调整)

If you really want to keep them as char* you can: 如果您真的想将它们保留为char* ,则可以:

i) allocate each one beforehand with malloc : 我)预先分配每个与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: ii)scanf到缓冲区,然后将结果复制到最终成员:

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);
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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