+ 1
Is there a way to either read what a cin says and convert that into a command, or is there a way to do a switch statement but
With a string?
5 ответов
+ 1
You can always go back to using an if - else if - else statement. A switch statement is basically the same, but it only works with types who have an integral representation. So instead of writing
switch ( string ) {
case "...": {}
case "....": {}
default: {}
}
you can write
if ( string == "..." ) {}
else if ( string == "...." ) {}
else {}
In this case, it might be a good idea to convert the string you got from the user to lowercase, so that you have to compare against less cases and it becomes redundant if a user enters "add" or "AdD". You can do this by applying the following snippet of code onto a string:
std::string s{ "Hello World!" };
std::transform (
s.begin(),
s.end(),
s.begin(),
::tolower
);
cout << s; // hello world!
If you want to do that, make sure to include both <algorithm> for std::transform() and <cctype> for std::tolower() as headers in your program.
0
You mean like input text and have it evaluated like code?
If that’s what you mean, that’s generally a very bad idea, because it’s unsafe to let users input any code they want.
0
I mean with a string, it can only be a char or an int, so if you want to run something where the user puts in a sentence or something, you cant put that cin into a switch and do certain commands with it
0
So like you can do
char y;
Int main () {
Cin >> y;
Switch (y) {
Case 'h' : cout << "you inputted h";
But you can't do
string y;
Int main() {
cin >> y;
Switch (y)
Case "this is a password" : cout <<"to you typed in password";
0
I'm basically trying to say is there a way to have a user input something longer than one character, and have it do something based on what the user said