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 variablegreeting
and initializes it with the text "Hello, ".std::string name;
: Declares another string variablename
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 variablename
.greeting += name;
: Concatenates thename
string to thegreeting
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 themain()
function.