Feb 6, 2022 at 1:29pm UTC
I have these words ( burger, hamburger, chips, Cola, Sprite), I need to write a function to take print like these:
Chose your order from (0 - 4)
0: Burger
1: Hamburger
2: Chips
3: Cola
4: Sprite
Thanks, Your order is complete!
Feb 6, 2022 at 1:53pm UTC
and your c++ issue is? Can you use std::cout to display the menu? Use std::cin to accept the order number?
Have you first designed the program so that you can code from the design?
What have you attempted so far?
Feb 6, 2022 at 3:57pm UTC
Can you clarify that you just want to print this output only or also want to store it?
If you just want to print it out then you can use switch statement and I can provide the code if you want.
Feb 6, 2022 at 5:13pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std::string_literals;
void DisplayMenu(const auto & stringArray) {
if (stringArray.size() < 2)
std::cout << "No menu to display!\n" ;
else {
for (size_t i {}; const auto & s : stringArray)
if (i++)
std::cout << " " << i - 1 << ") " << s << '\n' ;
else
std::cout << '\n' << s << '\n' ;
std::cout << "Enter option: " ;
}
}
auto Menu(const auto & stringArray) {
unsigned short response {};
const auto size {stringArray.size() - 1};
do {
std::istringstream is;
std::string input {};
do {
DisplayMenu(stringArray);
std::getline(std::cin, input);
is.clear();
is.str(input);
} while ((!(is >> response) || (is >> input)) && (std::cout << "Invalid input\n" ));
} while ((response < 1 || response > size) && (std::cout << "Invalid choice\n" ));
return response;
}
int main() {
const std::vector example {"Menu choices are:" s,
"Burger" s, "Hamburger" s,
"Chips" s, "Fries" s,
"Cola" s, "Sprite" s};
const auto choice {Menu(example)};
std::cout << "\nYou chose: " << example[choice] << '\n' ;
}
Last edited on Feb 6, 2022 at 5:14pm UTC