I'm writing this code that takes in a char userinput and uses the switch statement do execute the respective command. However because c switch statements can only read ints and enums, I'm not sure how to incorporate this. The user input must be a char. any ideas? I know charInput >> enumInput doesn't work but I'm not sure what to do.
int main (int argc, char** argv) {
enum charCommand {i,d,s,n,r,a,m,t,p,l,q};
charCommand enumInput;
while (mainLoop) {
cout << "enter valid input" endl;
char charInput;
printf("Enter a command: ");
cin >> charInput;
charInput >> enumInput;
switch (charInput) {
case i : {
printf("This is case i");
exit(0);
} //case i
default: {
cout << "invalid command, try again!\n";
}
}
};
}
CodePudding user response:
One way to accomplish this is to map the actual character entered to its corresponding enum
:
#include <map>
//...
int main (int argc, char** argv)
{
enum charCommand {i,d,s,n,r,a,m,t,p,l,q};
std::map<char, charCommand> charToEnumMap = {{'i',i},
{'d',d},
{'s',s}}; // Add the rest
charCommand enumInput;
while (mainLoop)
{
cout << "enter valid input" endl;
char charInput;
printf("Enter a command: ");
cin >> charInput;
auto iter = charToEnumMap.find(charInput);
if ( iter != charToEnumMap.end() )
{
switch (iter->second)
{
case i :
{
printf("This is case i");
exit(0);
} //case i
default:
{
cout << "invalid command, try again!\n";
}
}
}
}
}
CodePudding user response:
There's no need for an enum
here. switch
works with char because char
is convertible to int
. So if we define a char
as such:
char c = 'a';
..and then switch on it:
switch (c)
This works because 'a'
can be converted to int
(ASCII value). So this can also be written as:
switch (int(c)) // Same as switch (c)
Example:
#include <iostream>
int main(int argc, char** argv)
{
char input; std::cin >> input;
switch (input)
{
case 'a':
std::cout << 'a' << std::endl;
break;
case 'b':
std::cout << 'b' << std::endl;
break;
case 'c':
std::cout << 'c' << std::endl;
break;
default:
std::cout << "Some other key" << std::endl;
break;
}
}
The above example works. For your case, I would rewrite your program as:
#include <iostream>
int main(int argc, char** argv) {
while (true) {
std::cout << "enter valid input" << std::endl;
char charInput;
printf("Enter a command: ");
std::cin >> charInput;
switch (charInput) {
case 'i':
printf("This is case i");
exit(0); //case i
default:
std::cout << "invalid command, try again!\n";
break;
}
};
}
Also, consider not using the following in your code:
using namespace std;
..as it's considered as a bad practice. For more info on this, look up why is "using namespace std" considered as a bad practice.