I'm writing a menu that will present you with 5 choices over and over again until you enter 5 as your input to leave. My code deals with string inputs and such but when I enter a float number the program rounds it, stores it as an int, and does the loop a couple times in a weird way! Please help. I need to know how to deal with float inputs in my UI
#include "GameClass.h"
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
cout<<"This application stores a list of board games in stock for Wildcats Store."<<endl;
int choice = 0;
while(choice != 5)
{
cout<<"Select from:"<<endl;
cout<<"1.Insert a game record"<<endl;
cout<<"2.Delete a game record"<<endl;
cout<<"3.Print the game list"<<endl;
cout<<"4.Search the game list"<<endl;
cout<<"5.Quit"<<endl;
cin>>choice;
if (cin.fail())
{
cout<<"Sorry, that wasn't a valid input! Please enter an option 1,2,3,4,5"<<endl;
cin.clear();
string tempstr;
cin>>tempstr;
}
else
{
//Choice 1:Insert game record into the game list
if (choice == 1)
{
}
//Choice 2:Delete game specified by the user from the game list
if (choice == 2)
{
}
//Print all the games and their information in Lexogaphical order
if (choice == 3)
{
}
//Search the directory for a game mathing search key supplied by the user
if (choice == 4)
{
}
}
}
cout<<"Thank you for visiting the Wildcat Store!"<<endl;
system("pause");
return 0;
}
when I enter a float number the program rounds it, stores it as an int
Not quite. When a floating-point value is entered, the program reads only as far as the decimal point. Thus it truncates, rather than rounds the value. But the important part is that everything else from the decimal point onwards remains in the input buffer, and is picked up by the next cin statement.
Whether the user's input is valid or not, you need to empty the buffer.
You can do that by using ignore(). cin.ignore(1000, '\n');
is probably adequate, though a more general case is to use std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
You'll need to #include <limits> for that.
This will read and discard eveything up to and including the newline character.