How to print everything from a struct array in C ++?

I have a structured data type called bookStruct and books is the name of a variable associated with the bookStruct data type. book [10] is an array of 10 characters long and has 4 data characters, that is, book [0] for book [3] contains data in them when the rest are empty (o values). Now, I want to print the data that is already available in the array, rather than print the ones that are otherwise empty. I have tried the code below with no luck. What am I doing wrong here?

for (int i=0;i<MAX_BOOKS && books[i]!='\0';i++)
            {
                cout << "Book Title: " << books[i].bookTitle << endl;
                cout << "Total Pages: " << books[i].bookPageN << endl;
                cout << "Book Review: " << books[i].bookReview << endl;
                cout << "Book Price: " << books[i].bookPrice<< "\n\n" << endl;
            }

      

here is the declaration for the book struct

struct bookStruct
{
    string bookTitle;
    int bookPageN;
    int bookReview;
    float bookPrice;
};

bookStruct books[10];

      

+3


source to share


2 answers


It's a little difficult to say what is being asked here. You see, it's enough just to count how many books you have saved:

int numBooks = 0;

      

When you add a book, you increase numBooks

to MAX_BOOKS

.

for( int i=0; i<numBooks; i++ ) ...

      

If you don't want to do this, you certainly cannot test books[i] != '\0'

, because this checks the structure for one character.



Instead, you can test books[i].bookTitle.size() != 0

(or really !books[i].bookTitle.empty()

).

for( int i=0; i<MAX_BOOKS && !books[i].bookTitle.empty(); i++ ) ...

      

Another alternative is to store the books in vector

instead of an array, so you don't have to worry about max counts and current counts. The vector can shrink and grow for you.

vector<bookStruct> books;

...

for( int i = 0; i < books.size(); i++ ) ...

      

+4


source


Overload the output statement. For example:

struct Book {
    string title;
    int pageN;
    int review;
    float price;
};

ostream& operator<<(ostream& os, const Book& book) {
    return os << "Title: " << book.title << endl
              << "Pages: " << book.pageN << endl
              << "Review: " << book.review << endl
              << "Price:" << book.price << endl;
}

      

Then you can output to any stream:



Book book;
ostringstream oss;
oss << book;

      

To iterate over all your books by copying them to std::cout

, only if the book has a title, you need std::copy_if

:

bool bookHasTitle(const Book& book) {
    return book.title.empty() == false;
}

Book books[10];

copy_if(books, books+10, ostream_iterator<Book>(cout, "\n"),
        bookHasTitle);

      

+9


source







All Articles