Reputation:
My question is this: how do I set the default value in my function of type Enum, to be one of the values in the Enum. This is my first experience with Enumerations and enumerated functions. I know a decent amount about Intro/Beginner C++.
Example.. Setting the Default value to return HANDHELD ?
Also any advice on making better/clearer questions would be appreciated.
ComputerType SellerList::ReadAndReturnComputerType() const
{
char type[MAX_NAME_LEN];
cin >> type;
if(strcmp(type, "desktop") == 0)
return DESKTOP;
else if (strcmp(type, "laptop") == 0)
return LAPTOP;
else if(strcmp(type, "tablet") == 0)
return TABLET;
else if(strcmp(type, "handheld") == 0)
return HANDHELD;
}
Upvotes: 2
Views: 117
Reputation: 3778
Please don't do that kindda of stuff with strcmp
and else if
all over the place... You're doing c++ !
At least do something like the following piece of code. It's a lot more maintenable and with a bit of improvement you can handle the conversion enum/string and string/enum with the same map (you can even use bimap for this !).
#include <iostream>
#include <map>
#include <string>
enum ComputerType
{
DESKTOP,
LAPTOP,
TABLET,
HANDHELD
};
ComputerType ReadAndReturnComputerType()
{
// I assume this is not multithread othewise there wouldn't be any cin
static std::map<std::string, ComputerType> type {
{ "desktop", DESKTOP },
{ "laptop", LAPTOP },
{ "tablet", TABLET },
{ "handheld", HANDHELD } };
std::string input;
std::cin >> input;
auto it = type.find(input);
// Don't forget to clean the input here !
// something like:
//
// boost::trim(input);
// boost::to_lower(input);
if (type.end() == it)
{
return HANDHELD;
}
return it->second;
}
Upvotes: 1
Reputation: 46578
if you want set the default value before if statement
ComputerType SellerList::ReadAndReturnComputerType() const
{
ComputerType defType = HANDHELD;
char type[MAX_NAME_LEN];
cin >> type;
if(strcmp(type, "desktop") == 0)
type = DESKTOP;
else if (strcmp(type, "laptop") == 0)
type = LAPTOP;
else if(strcmp(type, "tablet") == 0)
type = TABLET;
else if(strcmp(type, "handheld") == 0)
type = HANDHELD;
return defType;
}
Upvotes: 0