Lesson 118 +40 XP

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 struct with string and int members
  • Creating a Book with 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

  1. Declare vector<Book> shelf;.
  2. shelf.push_back(first); and shelf.push_back(second);.
  3. Loop with for (const Book& b : shelf).
  4. Inside the loop print b.title << " by " << b.author << " (" << b.year << ")".
  5. Add one more book of your own using the brace style.
  6. Run it and confirm all three books print.

Checklist

  • [ ] The Book struct holds title, author, and year
  • [ ] Books live in a std::vector<Book>
  • [ ] push_back adds each book
  • [ ] A range-for loop prints every book
  • [ ] Braces initialize a book in one line
  • [ ] The program compiles and runs

TL;DR

  • A struct bundles related fields into one type.
  • Create an instance with Book b{"...", "...", 1949};.
  • push_back adds items to a vector.
  • for (const Book& b : books) visits each book without copying.