Fill data to array of Structures - C Structure

C examples for Structure:Structure Value

Description

Fill data to array of Structures

Demo Code

#include <stdio.h>
#include <string.h>
char * s_gets(char * st, int n);
#define MAXTITL   40//w  ww.  jav  a  2 s . co  m
#define MAXAUTL   40
#define MAXBKS   100              /* maximum number of books  */

struct book {                     /* set up book template     */
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
};

int main(void){
    struct book my[MAXBKS]; /* array of book structures */
    int count = 0;
    int index;
    
    while (count < MAXBKS && s_gets(my[count].title, MAXTITL) != NULL
           && my[count].title[0] != '\0')
    {
        printf("Now enter the author.\n");
        s_gets(my[count].author, MAXAUTL);
        printf("Now enter the value.\n");
        scanf("%f", &my[count++].value);
        while (getchar() != '\n')
            continue;          /* clear input line         */
        if (count < MAXBKS)
            printf("Enter the next title.\n");
    }
    
    if (count > 0)
    {
        printf("Here is the list of your books:\n");
        for (index = 0; index < count; index++)
            printf("%s by %s: $%.2f\n", my[index].title,my[index].author, my[index].value);
    }
    
    return 0;
}

char * s_gets(char * st, int n){
    char * ret_val;
    char * find;
    
    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        find = strchr(st, '\n');   // look for newline
        if (find)                  // if the address is not NULL,
            *find = '\0';          // place a null character there
        else
            while (getchar() != '\n')
                continue;          // dispose of rest of line
    }
    return ret_val;
}

Related Tutorials