Display Your Name in C++
Store a name in a C++ string and print it with cout.
1#include <iostream>2#include <string>3using namespace std;45int main() {6 string name = "John Doe";7 cout << "My name is: " << name << endl;8 return 0;9}
Output
My name is: John Doe
What's going on
This C++ program stores a name in a string and prints it with cout. Same skeleton as Hello World, plus a variable.
#include <iostream>
Needed for cout.
#include <string>
Needed for string. Some compilers pull it in through iostream. Others don't. Include it, or this file builds on one machine and dies on another.
using namespace std;
So string and cout don't need std::.
string name = "John Doe";
A variable holding text. = copies the literal in. Change the quotes, the output changes. This is not cin yet — the name is baked into the source.
cout << "My name is: " << name << endl;
Chain <<. First the label, then the variable, then endl (newline + flush). Forget endl and the next prompt glues onto this line.
Sample: name is "John Doe" → My name is: John Doe.
A C string char name[] = "John Doe"; also prints. string is the one you want for later input and concatenation.
Hard-coding the name is the demo. User Input is the version that reads it with cin.