c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

3rd Jan 2022, 4:47 PM
Mando
Mando - avatar
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
26th Jan 2022, 5:49 AM
Muhammad Alif Deva Rizqon
Muhammad Alif Deva Rizqon - avatar
+ 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; } }
3rd Jan 2022, 4:47 PM
Mando
Mando - avatar
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; }
3rd Jan 2022, 5:07 PM
Rellot's screwdriver
Rellot's screwdriver - avatar