I have a structured a data type called bookStruct and books is the name of the variable associated with the bookStruct data type. book[10] is the array that is 10 characters long and has 4 characters of data, meaning book[0] to book [3] have datas in them when the rest are empty (o values). Now I want to print the datas that are availabe already in the array and not print the ones that are empty otherwise 0. I tried the below code, 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 book struct
struct bookStruct
{
string bookTitle;
int bookPageN;
int bookReview;
float bookPrice;
};
bookStruct books[10];
It’s a little hard to tell what’s being asked here. You see, it’s quite easy to just keep count of how many books you have stored:
When you add a book, you increment
numBooksup untilMAX_BOOKS.If you don’t want to do that, you certainly can’t test
books[i] != '\0'because that is testing the struct against a single character.Instead, you might want to test
books[i].bookTitle.size() != 0(or indeed
!books[i].bookTitle.empty()).Another alternative is to store books in a
vectorinstead of an array, so you don’t have to worry about maximum counts and current counts. The vector can shrink and grow for you.