In: Computer Science
C++
function to a string into enum
function to a enum into a string
check valid / loop ( asking a couple of times until answer invaild)
For example
Enum Fruit ( APPLE, STRAWBERRY, BLUEBERRY, BLACKBERRY)
output should be
what is your favorit fruit? : strawberry
you will have STRAWBERRY.
what is your favorite fruite : peach
invaild
TIA
code:
#include <iostream>
#include <string>
#include<stdio.h>
#include <cstdlib>
using namespace std;
enum Fruit {APPLE,STRAWBERRY, BLUEBERRY, BLACKBERRY}; //declaration
of enum
Fruit val(const std::string& s) //function to
convert string into ennum
{
if(s=="APPLE"){
return APPLE;
}
else if(s=="STRAWBERRY"){ //checking string and returning enum
value
return STRAWBERRY;
}
else if(s=="BLUEBERRY"){
return BLUEBERRY;
}
else if(s=="BLACKBERRY"){
return BLACKBERRY;
}
else{
cout<<"Invalid";
}
}
Fruit con(Fruit v){
//function to convert enum
into string
switch(v){
case APPLE:
cout<<"Apple";
break;
case STRAWBERRY:
cout<<"STRAWBERRY";
break;
case BLUEBERRY:
//checking
enum to send string value
cout<<"BLUEBERRY";
break;
case BLACKBERRY:
cout<<"BLACKBERRY";
break;
default:
cout<<"No
such fruit";
break;
//break statement to stop
condition
}
}
int main()
{
string mystring; //string declaration
Fruit t; //creating object of
fruit
t=APPLE;
con(t); //passing enum value to con
function
cout<<"\n";
do{
cout<<"What is your favourite
fruit:";
cin >>
mystring;
Fruit f =
val(mystring); //passing string value to convert to enum
switch (f) {
case APPLE:
cout<<"You will have APPLE"<<"\n";
break;
case STRAWBERRY:
cout<<"You will have
STRAWBERRY"<<"\n";
break;
case BLUEBERRY:
cout<<"You will have
BLUEBERRY"<<"\n";
break;
case BLACKBERRY:
cout<<"You will have
BLACKBERRY"<<"\n";
break;
default:
exit(0); //to exit out of console
break;
}
} while(true);
return 0;
}
output:
code screenshot: