Why my "name" and "prodi" could not show up in queue

Viewed 20

I'm fairly new to learning C and my English isn't that good either but I need help in my code.

struct mahasiswa{
    char name;
    char prodi;
    int nim; 
}Mhs[maxsize];

void inQueue(){
    if(!isFull()){
        char name, prodi;
        int nim,i;
        printf("Input name mahasiswa: ");
        scanf("%s",&name);
        printf("Input NIM mahasiswa: ");
        scanf("%d",&nim);
        printf("Input Prodi mahasiswa: ");
        scanf("%s",&prodi); 
        Mhs[Queue.akhir].name = name;
        Mhs[Queue.akhir].nim = nim;
        Mhs[Queue.akhir].prodi = prodi;
        ++Queue.akhir;
        ++size;
        menu();
    }else {
        printf("Data penuh");
        menu();
    }
}

void tampil(){
    if(!isEmpty()){
        int i;
        for(i=0;i<Queue.akhir;i++){
        printf("\nNIM   : %d\n",Mhs[i].nim);
        printf("\nProdi : %s\n",Mhs[i].prodi);
        printf("\nName  : %s\n",Mhs[i].name);
        }
    }else {
        printf("\nemptydata k");
    }
    menu();
}

My int data could show up, but not with the string.

1 Answers

You need to actually store strings in your structs:

#define MAX_LEN 20
struct mahasiswa {
    char name[MAX_LEN];
    char prodi[MAX_LEN];
    int nim; 
} Mhs[maxsize];

Then you can read input as follows:

        char name[MAX_LEN];
        scanf("%s", name);

The & needs to be removed as the array decays to a pointer already. To avoid problems due to buffer overflow, you should also add a length limit:

        scanf("%19s", name);

That only reads and stores up to 19 characters + 0 byte which is maximum length for an array of size 20.

Then, you cannot assign a string just with an assignment as you do with integers. You need to use a function (don't forget to #include <string.h>):

        strcpy(Mhs[Queue.akhir].name, name);

As an alternative, you could drop the local array name at all and directly read into the structure:

        scanf("%19s", Mhs[Queue.akhir].name);

Same needs to be done for other strings.

Related