执行推回操作后打印出向量中的所有书籍

Ceb*_*ebu 1 c++

我试图创建一个程序,用户在其中键入书籍,然后将其存储到书架中。当用户键入“DONE”时,条目必须结束。

我想得到以下输出:

Welcome to your digital library!

Enter a book you would like to add: 
  Enter name: Harry Potter
  Enter author: Me
  Enter pages: 313

Enter a book you would like to add: 
  Enter name: Lord of the rings
  Enter author: Tolkien
  Enter pages: 412

Enter a book you would like to add: 
  Enter name: DONE

The following books are available in your bookshelf:

1. Harry Potter written by Me. Pages: 313
2. Lord of the rings written by Tolkien. Pages: 412
Run Code Online (Sandbox Code Playgroud)

但我只得到第一本输入的书,所以我只会得到:

The following books are available in your bookshelf:
    
    1. Harry Potter written by Me. Pages: 313
Run Code Online (Sandbox Code Playgroud)

这是为什么?我为每个 get(book) 执行一次 Push_back,在 while 循环完成后,我在有效的 for 循环中打印出所有书籍。我的程序出了什么问题?

这是我的代码:

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

using namespace std;

struct Book_Type{
    
    string name;
    string author;
    int pages;
};

bool get (Book_Type & book)
{
    
    cout << endl << "Enter a book you would like to add: " << endl
         << setw(14) << "Enter name: ";
    getline(cin,book.name);
    
    if (book.name == "DONE")
    {   
        cout << endl;
        return false;
    }
    
    cout << setw(16) << "Enter author: ";
    getline(cin,book.author);
    
    cout << setw(15) << "Enter pages: ";
    cin >> book.pages;
    cin.ignore(1);
    
    return true;

}

void add (vector<Book_Type> & book_shelf,
          Book_Type const & book)
{
    book_shelf.push_back(book);
}



void put (vector<Book_Type> const & book_shelf,
          Book_Type const & book)
{
    int num {};
    
    cout << "The following books are available in your bookshelf:" << endl << endl;
    
    for (Book_Type book : book_shelf)
    {
        num++;
        
        cout << num << ". " << book.name 
             << " written by " << book.author
             << ". Pages: " << book.pages << endl;
    }
}




int main()
{
    Book_Type book {};
    vector<Book_Type> book_shelf {};
    
    cout << "Welcome to your digital library!" << endl;
    
    while (get(book))
    {
        get(book);
        add(book_shelf,book);
    }
    
    put(book_shelf,book);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

BoP*_*BoP 6

while (get(book))
{
    get(book);
    add(book_shelf,book);
}
Run Code Online (Sandbox Code Playgroud)

这看起来就像您调用了get(book)两次,但仅将其他所有书籍添加到书架中。这样你就会失去一半的书。