Description
Please write a program that defines a structure called book, which contains two members: bname and price. Then, input the number of books and allocate memory using malloc to store the data of these books.
請撰寫一支程式,先定義結構 book,內含兩個成員 bname 和 price,接著輸入書本的數量並以 malloc 配置需要的記憶體空間來存放這些書籍資料。
Finally, print out the names and prices of all the books.
最後請印出所有所有書本書名與他的價格。
Input
The first line contains an integer, n, representing the number of books. Then, there are n sets of data. Each set consists of two lines: the first line is the book name, and the second line is the price of the book.
第一行包含一個數字 n ,代表書本的數量。接下來有 n 組資料,每組資料兩行,第一行為書名,第二行則為該書籍的價格。
Output
For each book data, print out the book name and its price in the format "book name: price", one data per line. There is no newline after the last data.
對於每個書籍資料,以 "書名: 價格" 的格式印出,一筆資料一行。最後一筆資料後面沒有換行。
Sample Input 1
10
Pride and Prejudice
500
The Catcher in the Rye
730
To Kill a Mockingbird
479
The Lord of the Rings
399
The Chronicles of Narnia
700
Moby-Dick
1490
The Hobbit
499
War and Peace
1234
The Hitchhiker's Guide to the Galaxy
1000
Brave New World
700
Sample Output 1
Pride and Prejudice: 500
The Catcher in the Rye: 730
To Kill a Mockingbird: 479
The Lord of the Rings: 399
The Chronicles of Narnia: 700
Moby-Dick: 1490
The Hobbit: 499
War and Peace: 1234
The Hitchhiker's Guide to the Galaxy: 1000
Brave New World: 700
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book {
char bname[1000];
int price;
};
int main() {
int n;
// Read the number of books
scanf("%d", &n);
// Dynamically allocate memory for an array of struct book
struct book *books = (struct book*)malloc(n * sizeof(struct book));
// Input book names and prices
getchar(); // Consume the newline character left in the input buffer
for (int i = 0; i < n; i++) {
// Read book name
fgets(books[i].bname, sizeof(books[i].bname), stdin);
// Remove trailing newline character
if (books[i].bname[strlen(books[i].bname) - 1] == '\\n')
books[i].bname[strlen(books[i].bname) - 1] = '\\0';
// Read book price
scanf("%d", &books[i].price);
getchar(); // Consume the newline character left in the input buffer
}
// Output book names and prices
for (int i = 0; i < n; i++) {
printf("%s: %d\\n", books[i].bname, books[i].price);
}
// Free dynamically allocated memory
free(books);
return 0;
}