how to accept only whole numbers in c++ -
i new programming , need term project. have made program simulates hotel booking, problem whenever non-whole number entered first question, goes infinite loop. if second question , enter non-whole number accepts whole number dropping off comes after decimal , skips next question , stops running program.
#include <iostream> #include <string> using namespace std; int stay_length (int stay) { int nights = stay; int total = 0*nights; return total; } int rooms_booking(int rooms) { int rooms_booked = rooms; int total = 0; if(rooms_booked > 0) { total = rooms_booked * 50; } else { total = 0; } return total; } int main(){ int x; string repeat; int nights; int total = 0; int rooms_avail = 10; int rooms; cout << "hello! welcome hotel comp 150." << endl; { if (rooms_avail > 0) { cout << "how many nights staying?" << endl; } else { cout << "sorry, there no rooms available. " << endl; } { cin >> nights; if (nights > 0 && nights <= 28) { int total1 = stay_length(nights); cout << "you staying " << nights << " nights" << endl; cout << "that costs: $" << total1 << endl; total = total + total1; } else { cout << "you cannot stay less 1 or more 28 nights" << endl; } } while (nights <= 0 || nights >28); if (rooms_avail > 0) { cout << "how many rooms booking?" << endl; cout << "there " << rooms_avail << " available." << endl; cin >> rooms; if (rooms > 0 && rooms <= rooms_avail) { int total2 = rooms_booking(rooms); cout << "you booking " << rooms << " rooms." << endl; cout << "that costs : $" << total2 << endl; total = total + total2; rooms_avail = rooms_avail - rooms; } else if (rooms <= 0 || rooms > rooms_avail) { do{ cout << "you can book minimum of 1 room or maximum of " << rooms_avail << endl; cin >> rooms; } while (rooms <= 0 || rooms > rooms_avail ); int total2 = rooms_booking(rooms); cout << "you booking " << rooms << " rooms." << endl; cout << "that costs : $" << total2 << endl; total = total + total2; rooms_avail = rooms_avail - rooms; } else { cout << "you cannot book more " << rooms_avail << endl; } } else { cout << "sorry, rooms have been booked." << endl; } cout << "your total far is: $" << total << endl; cout << "would make booking? enter 'y' or 'y' so." << endl; cin >> repeat; }while(repeat == "y" || repeat == "y"); return 0; }
it's better use std::getline()
instead of operator>>
read interactive input std::cin
.
operator>>
not reading single line of text standard input, , storing it. that's std::getline()
for.
if wrong kind of input entered, not operator>>
expects, sets std::cin
failed state, makes future attempts read std::cin
fail, resulting in infinite loop observing.
to correctly, going either:
1) check fail()
after every operator>>
, see if input failed, if recover error clear()
, ignore()
. gets real old, quickly.
2) it's easier read single line of text std::getline()
, parse input yourself. construct std::istringstream
, if wish, , use operator>>
that, if makes easier you.
Comments
Post a Comment