how to use string in if else statement c++

To use a string in an if-else statement in C++, follow these steps:

  1. Declare and initialize a string variable:
std::string myString = "Hello";

Here, we declare a string variable named myString and initialize it with the value "Hello".

  1. Use the string variable in the if-else statement:
if (myString == "Hello") {
    // code to be executed if the condition is true
    std::cout << "The string is 'Hello'" << std::endl;
} else {
    // code to be executed if the condition is false
    std::cout << "The string is not 'Hello'" << std::endl;
}

In this example, we check if the value of myString is equal to "Hello". If it is, the code inside the if block will be executed and the message "The string is 'Hello'" will be printed. If the condition is false, the code inside the else block will be executed and the message "The string is not 'Hello'" will be printed.

  1. Compile and run the code: Make sure to include the necessary header file (<iostream>) at the beginning of your program and use the std namespace to avoid explicit use of the std scope.

Here's the complete code example:

#include <iostream>
#include <string>

int main() {
    std::string myString = "Hello";

    if (myString == "Hello") {
        std::cout << "The string is 'Hello'" << std::endl;
    } else {
        std::cout << "The string is not 'Hello'" << std::endl;
    }

    return 0;
}

Compile and run the code, and it will output:

The string is 'Hello'

This is because the value of myString is indeed "Hello", so the if condition evaluates to true and the code inside the if block is executed.