In this program, we will display a menu to the user. The user can choose any option from the given menu. The
menu would be something like this:
Welcome to the World of Control Structures
• Press (A) to add two integers
• Press (S) to subtract two integers
• Press (M) to multiply two integers
• Press (E) to exit the program
#include <iostream>
void PrintMenu()
{
std::cout << "Welcome to the World of Control Structures\n";
std::cout << "- Press (A) to add two integers\n";
std::cout << "- Press (S) to subtract two integers\n";
std::cout << "- Press (M) to multiply two integers\n";
std::cout << "- Press (E) to exit the program\n";
}
int main()
{
while(true)
{
PrintMenu();
char operation;
std::cin >> operation;
if(operation != 'A' && operation != 'S' && operation != 'M' && operation != 'E')
{
std::cout << "Unexpected input. Try again\n\n";
continue;
}
if(operation == 'E')
{
break;
}
int number1, number2;
std::cout << "Enter two numbers: ";
std::cin >> number1 >> number2;
if(!std::cin)
{
std::cout << "Bad input. Exit program\n";
return 1;
}
switch(operation)
{
case 'A' : std::cout << number1 << " + " << number2 << " = " << number1 + number2; break;
case 'S' : std::cout << number1 << " - " << number2 << " = " << number1 - number2; break;
case 'M' : std::cout << number1 << " * " << number2 << " = " << number1 * number2; break;
}
std::cout << "\n\n";
}
return 0;
}
Comments
Leave a comment