Input Strings and Operations

Hey Guys

Just another issue with C++ that I need help with.

How do you program that if the user enters a particular string, an operation occurs.

For example 1: if the user inputs the string 'name', I want the output to be (for instance) "Tom"

For example 2: if the user inputs the sring 'hello', I want the output to be "Nice to meet you"


So how would you perform the functions above and would it be best using an if statement. If so how?

Thanks for your help

Strings are so hard to manipulate aren't they?
Well that doesn't really require any manipulation of the strings, that really just requires comparisons. For something that simple, a switch statement should suffice. Here is how to use them with the examples you gave

1
2
3
4
switch( input ) {
   case( "name" ): cout << "Tom" << endl; break;
   case( "hello" ): cout << "Nice to meet you" << endl; break;
}


etc.
Last edited on
Use compare(), a member function of the class string. There's an example on this page

http://www.cplusplus.com/reference/string/string/compare/

Go through the reference page and the sample code. If you don't understand, post here again.
Last edited on
@Tevsky
switch works only with integral types
@wizard25
If using C++ strings you can use the == operator:
1
2
3
4
if ( mystring == "name")
    //do something
else if ( mystring == "hello" )
   //do something else 

Topic archived. No new replies allowed.