'how do i input string in Linked List

im curently working on linked list but to input some string ive veeb trying several ways to do it , i dont know what makes them error

this is my current code

struct barang{
    char namabarang[30];
    int hargabarang;
    int idbarang;
    struct barang* next;
};
struct barang *head;

void input()
{
    struct barang *ptr;
    char nama[30];
    int harga,id;

    ptr = (struct barang*)malloc(sizeof(struct barang *));
    if(ptr == NULL)
    {
        printf("\n\n\tOVERFLOW!");
    }
    else
    {
        printf("\n\n\tSilahkan Masukan\n");
        printf("\tNama barang  : ");
        fflush(stdin);
        scanf("%[^\n]",nama);
        strcpy(ptr ->namabarang,nama);
        ptr-> next = head;
        head = ptr;
        printf("\n\tData Berhasil Disimpan di NODE awal!");
    }
}


Solution 1:[1]

You are never consuming any newlines, so all the scanf after the first are not reading any data. Probably the simplest solution is to modify the scanf to be:

if( scanf(" %29[^\n]", ptr->namabarang ) != 1 ){
    fprintf(stderr, "Invalid input\n");
    exit(1);
}

By writing directly to ptr->namabrang, you can omit the strcpy. Adding the leading whitespace in the format specifier will cause subsequent scanf to consume the newlines, but will also trim any leading white space. If that is a problem, you should STOP USING SCANF. You should not be using scanf in any case, but that's another discussion. Also, adding the width modifier will prevent a buffer overflow.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 William Pursell