#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "John Doe";
cout << "My name is: " << name << endl;
return 0;
}Output
My name is: John Doe
Display Your Name in C++
This program teaches you how to store text in a variable and display it on the screen. It is simple and perfect for beginners who are learning about strings, variables, and cout.
1. Header Files
There are two header files in this program:
-
#include <iostream>
This header allows us to use cout for output. -
#include <string>
This header allows us to use the string data type in C++.
Without this, the program would not understand what a string is.
Header files bring ready-made tools into our program so that we can use them.
2. using namespace std;
This line allows us to use names like cout and string without writing std:: before them.
- Without it, we would have to write: std::cout, std::string
- With it, we can simply write: cout, string
It makes the code easier and shorter for beginners.
3. main() Function
Every C++ program starts running from the main() function.
The line:
int main() {
marks the beginning of the program.
Everything inside the curly braces { } is what the computer will run.
4. Declaring a String Variable
Inside main, we have:
string name = "John Doe";
Here's what this means:
- string is a data type that stores text (words, sentences, names, etc.).
- name is the variable where the text will be stored.
- "John Doe" is the actual text we are saving inside the variable.
You can think of a variable like a small box that holds information.
So this line is simply saying: "Create a box named name and put the text 'John Doe' inside it."
You can change "John Doe" to your own name.
5. Displaying the Name Using cout
The next line is:
cout << "My name is: " << name << endl;
This line prints the message on the screen.
Let's break it down:
- cout: Used to show output on the screen.
- <<: This is called the insertion operator. It sends data to cout.
- "My name is: ": This is a string literal (fixed text).
- name: This is our variable containing "John Doe".
- <<: Another insertion operator.
- endl: This adds a new line after printing (like pressing Enter).
So the entire line means: "Print 'My name is: ', then print the value stored in name, then go to a new line."
6. return 0;
This line tells the operating system that the program ended successfully.
Key Takeaways
#include <string> is needed to use string variablesstring data type stores textVariables store values that can be used later
cout can print multiple items using <<endl adds a new line to the output