C++ String Example

#include <iostream>
#include <string>

int main() {
    std::string greeting = "Hello, ";
    std::string name;

    std::cout << "Please enter your name: ";
    std::cin >> name;

    greeting += name;

    std::cout << greeting << std::endl;

    return 0;
}

Explanation:

  • #include <iostream> and #include <string>: These lines include necessary libraries for input/output and string manipulation.

  • int main() { ... }: This is the main function where the program begins its execution.

  • std::string greeting = "Hello, ";: Declares a string variable greeting and initializes it with the text "Hello, ".

  • std::string name;: Declares another string variable name without initializing it.

  • std::cout << "Please enter your name: ";: Outputs a prompt to enter a name on the console.

  • std::cin >> name;: Reads the user input from the console and stores it in the variable name.

  • greeting += name;: Concatenates the name string to the greeting string using the += operator.

  • std::cout << greeting << std::endl;: Outputs the concatenated greeting (Hello, [name]) to the console, followed by an endline.

  • return 0;: Indicates successful termination of the main() function.