Beginner char Menu function
May 14, 2020 at 6:35am UTC
I'm still not that with functions,i know i'm doing something wrong here. i'm trying to write a menu function that the user has to enter a character and if statement checks what the user chose and redirects them.
when i enter any of the options it just exits!?
what am i doing wrong?
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
#include <iostream>
using namespace std;
main()
{
char choice;
menu(choice);
if (choice=='A' ){
//do A
}
else
if (choice=='B' ){
//do B
}
...
return 0;
}
char menu(char c)
{
cout<<"A.Count Vowels Characters" <<endl;
cout<<"B.Find Cos(X)" <<endl;
cout<<"C.Print a triangle" <<endl;
cout<<"D.Average of Primes" <<endl;
cout<<"E.Exit" <<endl;
cin>>c;
return c;
}
Last edited on May 14, 2020 at 6:37am UTC
May 14, 2020 at 7:06am UTC
> menu(choice);
...
> char menu(char c)
..
> return c;
When you return something, the caller needs to be part of an assignment or comparison to make use of the returned value.
So perhaps
choice = menu(choice);
But passing a parameter as a substitute for a local variable is a poor way to go.
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
#include <iostream>
using namespace std;
char menu(void )
{
char c;
cout<<"A.Count Vowels Characters" <<endl;
cout<<"B.Find Cos(X)" <<endl;
cout<<"C.Print a triangle" <<endl;
cout<<"D.Average of Primes" <<endl;
cout<<"E.Exit" <<endl;
cin>>c;
return c;
}
int main()
{
char choice;
choice = menu();
if (choice=='A' ){
//do A
}
else
if (choice=='B' ){
//do B
}
...
return 0;
}
May 14, 2020 at 7:20am UTC
so what do you propose is a better way to go about it ?
May 14, 2020 at 8:18am 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 53 54 55 56 57 58 59 60 61 62
#include <iostream>
using namespace std;
void function_A()
{
cout << "Do something *** AAA *** ...\n" ;
return ;
}
void function_B()
{
cout << "Do something *** BBB *** ...\n" ;
return ;
}
void displayMenu()
{
cout << "\nPLEASE SELECT FROM\n" ;
cout<<"A.Count Vowels Characters" <<endl;
cout<<"B.Find Cos(X)" <<endl;
cout<<"C.Print a triangle" <<endl;
cout<<"D.Average of Primes" <<endl;
cout<<"E.Exit\n" ;
return ;
}
char select_item()
{
char aSelection{};
cin >> aSelection;
aSelection = toupper(aSelection);
switch ( aSelection)
{
case 'A' :
function_A();
break ;
case 'B' :
function_B();
break ;
case 'E' :
break ;
default :
cout << "Invalid choice\n" ;
}
return aSelection;
}
int main()
{
char selection{};
while (selection != 'E' )
{
displayMenu();
selection = select_item();
}
cout << "The end\n" ;
return 0;
}
May 14, 2020 at 9:15am UTC
Thanks :)
Topic archived. No new replies allowed.