+ 1
c++
You are making a digital menu, which takes a number as user input, and outputs the corresponding menu item. However, the users can input anything, even numbers that are not present in the menu. Handle wrong user input, by throwing an exception with code 404 and outputting "404 - not found", if it is out of the range of the given menu.
3 Answers
+ 5
#include <iostream>
using namespace std;
int main() {
string menu[] = {"fruits", "chicken", "fish", "cake"};
try {
int x;
cin >> x;
int sizeArr = sizeof(menu)/sizeof(string);
if ( x >= sizeArr ) {
throw x;
}
cout << menu[x] << endl;
}
catch(...) {
//and here
cout << "404 - not found" << endl;
}
}
Good Luck
+ 2
#include <iostream>
using namespace std;
int main() {
string menu[] = {"fruits", "chicken", "fish", "cake"};
try {
int x;
cin >> x;
if (x>5){
throw 404;
}
cout << [x] << endl;
}
catch(int x) {
cout << "404 - not found" << endl;
}
}
0
add the else statement because even if you input more than 5, then it will try to execute the statement which you don't want to. also add the menu array with index as x - 1 since array starts at 0, not 1.
here's the example:
else {
cout << menu[x - 1] << endl;
}