Loading lessons...
Project 6: Book Store with structs
Project 6: Book Store with structs
A struct groups several related values under one name. A book has a title, an author, and a year, so a Book struct keeps all three together and easy to move around.
The goal
Define a Book struct, create a small vector of books, and print every book on its own line.
What you practice
- Declaring a
structwithstringandintmembers - Creating a
Bookwith braces:Book b{"1984", "George Orwell", 1949}; - Pushing books into a
std::vector<Book> - Printing each book with a range-for loop
Starter code
This compiles as-is:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Book {
string title;
string author;
int year;
};
int main() {
Book first;
first.title = "The Hobbit";
first.author = "J. R. R. Tolkien";
first.year = 1937;
Book second{"1984", "George Orwell", 1949};
cout << first.title << " (" << first.year << ")" << endl;
cout << second.title << " (" << second.year << ")" << endl;
return 0;
}
Step-by-step
- Declare
vector<Book> shelf;. shelf.push_back(first);andshelf.push_back(second);.- Loop with
for (const Book& b : shelf). - Inside the loop print
b.title << " by " << b.author << " (" << b.year << ")". - Add one more book of your own using the brace style.
- Run it and confirm all three books print.
Checklist
- [ ] The
Bookstruct holds title, author, and year - [ ] Books live in a
std::vector<Book> - [ ]
push_backadds each book - [ ] A range-for loop prints every book
- [ ] Braces initialize a book in one line
- [ ] The program compiles and runs
TL;DR
- A
structbundles related fields into one type. - Create an instance with
Book b{"...", "...", 1949};. push_backadds items to a vector.for (const Book& b : books)visits each book without copying.