A simple menu-based program.
Code:
#include <string>
#include <iostream>
using namespace std;
bool StringToInt( string s, int& pInt );
int menu();
int main(int argc, char *argv[])
{
string line;
int choice = menu();
cout << "Your choice: " << choice << endl;
cout << "Press Return to continue..." ;
getline( cin, line );
}
/*
* Displays the menu and allows the user to make a choice.
*/
int menu()
{
int choice;
string line;
while( true )
{
cout << "\nChoose your favourite hero!\n\n"
" 1\tBatman\n\n"
" 2\tSpiderman\n\n"
" 3\tThe Incredible Hulk\n\n"
" 4\tWolverine\n\n"
" 5\tBritney Spears\n\n"
"Your choice [a/b/c/d]: ";
getline( cin, line );
if( StringToInt(line, choice) == true )
{
if( choice < 0 || choice > 5 )
cout << "Please only enter numbers between 0 to 5 !\n";
else
return choice;
}
else
cout << "Please only enter integers!\n";
cout << "Press Return to continue..." ;
getline( cin, line );
}
}
/**
* Converts a string to an integer.
* If the conversion fails, return false.
*/
bool StringToInt( string s, int& pInt )
{
char * end ;
const char* start = s.c_str();
pInt = strtol( start, &end, 0 );
if ( start == end ) // end pointer left at start; totally invalid number
return false;
if ( *end ) // end pointer left in middle; partially invalid number
return false;
return true; // end pointer left at end; a valid number
}
and how do i set a variable so that it can be a decimal number?
Use a float or double type.