I have a program that needs to read 3 attributes from the user. It can read the first 2 just fine, when it tries to read the 3rd attribute (a double) it freezes until you enter an integer.
Here is the code
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <iomanip>
using namespace std;
#include <string>
#include "book.h"
Book::Book(const std::string &serialNo, const std::string &title, double price) : serialNo(serialNo), title(title),
price(price) {}
const std::string &Book::getSerialNo() const {
return serialNo;
}
void Book::setSerialNo(const std::string &serialNo) {
Book::serialNo = serialNo;
}
const std::string &Book::getTitle() const {
return title;
}
void Book::setTitle(const std::string &title) {
Book::title = title;
}
double Book::getPrice() const {
double scale = .1;
return (int)(price / scale) * scale;
}
void Book::setPrice(double price) {
Book::price = price;
}
map<string, Book *> addNewBook(map<string, Book *> inventory) {
printf("**Add New Book**\n\nNote: Type quit and enter on the serial no. to return to the Main Menu\n");
string serialNo, title;
double price;
while(serialNo != "quit") {
printf("Serial No.:");
cin >> serialNo;
if (serialNo == "quit") {
continue;
}
cin.clear();
cin.ignore(100, '\n');
printf("\nTitle: ");
getline(cin, title);
printf("\nPrice: ");
cin.clear();
cin.ignore(100, '\n');
cin >> price;
if (inventory.find(serialNo) == inventory.end()) {
inventory[serialNo] = new Book(serialNo, title, price);
} else {
printf("Serial No. exist already, please enter again:\n");
}
cin.clear();
cin.ignore(100, '\n');
}
return inventory;
}
int main() {
map<string, Book*> inventory;
addNewBook(inventory);
}
If you enter some string for the first 2 inputs, and something like 2.5 for the 3rd it will hang until you enter something like 12.
How do I prevent the hang and have it read the 2.5?