Odpowiedź na przechowywanie informacji w tablicy
#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 ("\n\nThe 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 : %s\n", books[i].author);
printf (" pages : %d\n", books[i].pages);
printf (" price : %ld\n", books[i].price);
i++;
}
printf ("\n");
return 0;
}
Zealous Zebra