Answers for "Answer to storing information in array"

C
0

Answer to storing information in array

#include <stdio.h>

#define MAXS 256

struct book
{
    char bname[20];
    int pages;
    char author[20];
    long price; 
};

int main () {

    struct book books[MAXS] = {{ {0}, 0, {0}, 0 }}; /* initialize all values to zero (null) */
    int nbooks = 0;
    int i = 0;

    printf ("nEnter number of books to store: ");
    scanf("%d%*c",&nbooks);                         /* read nbooks, and consume newline     */

    if (nbooks < 1) {                               /* validate number of books to enter    */
        fprintf (stderr, "error: invalid entry for 'nbooks'n");
        return 1;
    }

    for (i = 0; i < nbooks; i++)                    /* enter values for each book, use      */
    {                                               /* scanf to read each value AND the     */
        printf ("n  book[%2d] name  : ", i + 1);   /* newline character, emptying stdin    */
        scanf ("%[^n]%*c", books[i].bname);        /* after each read.                     */
        printf ("  book[%2d] pages : ", i + 1);
        scanf ("%d%*c", &books[i].pages);
        printf ("  book[%2d] author: ", i + 1);
        scanf ("%[^n]%*c", books[i].author);
        printf ("  book[%2d] price : ", i + 1);
        scanf ("%ld%*c", &books[i].price);
    }

    printf ("nnThe Books Entered Were:n");       /* output info for each book entered    */
    i = 0;
    while (*books[i].bname)
    {
        printf ("n  Book %-3d "%s"n", i + 1, books[i].bname);
        printf ("    author : %sn", books[i].author);
        printf ("    pages  : %dn", books[i].pages);
        printf ("    price  : %ldn", books[i].price);
        i++;
    }

    printf ("n");

    return 0;
}
Posted by: Guest on January-20-2022

Code answers related to "Answer to storing information in array"

Code answers related to "C"

Browse Popular Code Answers by Language