struct book { char title[MAXTITL]; char author[MAXAUTL]; float value; };
int main(void) { struct book library[MAXBKS]; int count=0, index;
printf("Please enter the book title, press [enter] at the start" " of a line to stop.\n"); while(fgets(library[count].title, MAXTITL-1, stdin)!= NULL && library[count].title[0] != '\n' && count<MAXBKS){ library[count].title[strlen(library[count].title)-1] = '\0'; printf("Now, enter the author: "); fgets(library[count].author, MAXAUTL-1, stdin); library[count].author[strlen(library[count].author)-1] = '\0'; printf("Now, enter the value: "); scanf("%f", &library[count++].value); if(getchar() == '\n') ; printf("Now, enter the title: "); } if(count > 0){ printf("Here is the list of your books: \n"); for(index=0; index<count; index++); printf("%s by %s: $%.2f.\n", library[index].title, library[index].author, library[index].value); } else printf("No books? So bad...\nBye Bye!\n");
return 0; }
这是我之前写的同样功能的代码,是我预想的结果。可是找不到两段代码的差异
int main(void) { struct book library[MAXBKS]; int count=0, index;
printf("Please enter the book title. Please ENTER at the start of" " line to quit.\n"); while(fgets(library[count].title, MAXTITL-1, stdin) != NULL && library[count].title[0] != '\n' && count<MAXBKS){ library[count].title[strlen(library[count].title)-1] = '\0'; printf("Now enter the author: "); fgets(library[count].author, MAXAUTL-1, stdin); library[count].author[strlen(library[count].author)-1] = '\0'; printf("Now enter the value: "); scanf("%f", &library[count++].value); if(getchar() == '\n') ; printf("Enter the next title: "); } if(count > 0){ printf("Here is the list of your books: \n"); for(index=0; index<count; index++) printf("%s by %s: $%.2f.\n", library[index].title, library[index].author, library[index].value); } else printf("No books? Too bad.\n");