#include<iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int optionChosen=0;
struct bookStruct
{
string bookTitle;
int bookPageN;
int bookReview;
float bookPrice;
};
const int MAX_BOOKS=10;
int main()
{
bookStruct books[10]={};
do
{
cout << "Please Select an Option from the Menu:\n\n" << endl;
cout << "1. Display List of Books.\n" << "2. Find Book.\n" << "3. Add New Book.\n";
cout << "4. Delete Book.\n"<<"5. Save List to File.\n"<<"6. Load List from File.\n";
cout << "7. Sort List.\n"<<"8. Exit.\n\n";
cin >> optionChosen;
switch(optionChosen)
{
case 1:
{
for (int i=0;i<MAX_BOOKS;i++)
{
if(books[i].bookTitle!="\0")
{
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;
}
}
break;
}
case 2:
{
}
case 3:
{
for(int i=0;i<MAX_BOOKS;i++)
{
if(books[i].bookTitle=="\0")
{
cout << "\nPlease Enter the Title: ";
cin >> books[i].bookTitle ;
cout << "\nPlease Enter Total Number of Pages: ";
cin >> books[i].bookPageN ;
cout << "\nPlease Enter Rating (stars): ";
cin >> books[i].bookReview ;
cout << "\nPlease Enter Price: ";
cin >> books[i].bookPrice;
cout << "\n\nBook Added.\n\n";
break;
}
}break;
}
case 4:
{
}
case 5:
{
}
case 6:
{
}
case 7:
{
}
default:
{
if(optionChosen!=8)
{
cout << "Wrong Input Chosen\n";
break;
}
}
}
}
while(optionChosen<=8);
return 0;
}
Here is my code. 2 Question…..1. When I press anything that is not a number (a,b,c,abc) as an option, the program executes an infinite loop (maybe) and doesnt stop. Q#2. When I am adding a book, if I use space, the code does the same thing (executes possible infinite loop) and never stops. What am I doing wrong here?
The first one is easy. When you
cin >> some_int;and there’s nointin the input stream, it simply fails and leaves the input stream in its current state.That means the the next time you go back to get another
int, it will still have the non-integer ready for reading.