Book Array
cin.ignore()skips (ignores) the next character in the input buffer. In this case we're ignoring the newline character ('\n') left in the buffer after reading input withstd::cin. This ensures that subsequent calls tostd::getlinework correctly without immediately capturing the leftover newline character.
Add "display_info" function to the Book struct that prints the title, author, and page_count of the book
Add "display_info" function to the Book struct that prints the title, author, and page_count of the book
Define a Book struct that includes the member variables: title, author, and page_count. Create an array of 3 Book objects, set their member variables, and print the details of each book in the array using a loop.
You can initialize the array with specific values directly or use std::cin to input the values.
Hint
Use std::getline to properly read the title and author strings with spaces if you're using std::cin to input the values.
Answer
#include <iostream>
#include <string>
struct Book {
std::string title;
std::string author;
int page_count;
};
int main() {
Book books[3];
for (int i = 0; i < 3; ++i) {
std::cout << "Enter the title of book " << i+1 << ": ";
std::cin.ignore();
std::getline(std::cin, books[i].title);
std::cout << "Enter the author of book " << i+1 << ": ";
std::getline(std::cin, books[i].author);
std::cout << "Enter the page count of book " << i+1 << ": ";
std::cin >> books[i].page_count;
}
std::cout << "\nBook Details:\n";
for (int i = 0; i < 3; ++i) {
std::cout << "Book " << i+1 << ":\n";
std::cout << "Title: " << books[i].title << std::endl;
std::cout << "Author: " << books[i].author << std::endl;
std::cout << "Page Count: " << books[i].page_count << std::endl;
std::cout << std::endl;
}
return 0;
}