Printing your own name is one of the simplest C++ programs. It demonstrates how to display text on the console using different output methods.
- Uses the cout object to display text on the screen.
- Demonstrates basic output operations in C++.
#include <iostream>
using namespace std;
int main() {
cout << "Alice";
return 0;
}
Output
Alice
Explanation: The string is sent to the standard output stream using the insertion operator (<<).
Syntax
The simplest way to print something is to use the cout. It is the standard method to output any data in C++.
cout <<"your_name";
Other Ways to Print Your Name
Apart from cout object there are also the various methods by which we can print your own name.
Using printf()
C++ supports the printf() function from the C language which can be used to print name on the output screen. It is defined inside the <cstdio> header file.
Syntax
printf("your_name");
#include <bits/stdc++.h>
using namespace std;
int main() {
// Printing the name using printf() method
printf("Anmol");
return 0;
}
Output
Anmol
Explanation: The string passed to printf() is displayed directly on the output screen.
Using puts()
The puts() function prints a string followed by a newline character. It is also defined in the <cstdio> header file.
Syntax
puts("your_name")
#include <bits/stdc++.h>
using namespace std;
int main() {
// Printing the name using puts function
puts("Anmol");
return 0;
}
Output
Anmol
Explanation: The string is printed on the screen, and the cursor automatically moves to the next line.
Using wcout
The wcout object is used to display wide characters and wide strings. It is useful when working with Unicode or multilingual text.
Syntax
wcout << L"your_name";
#include <bits/stdc++.h>
using namespace std;
int main() {
// Printing the string using wcout object
wcout << L"Anmol";
return 0;
}
Output
Anmol
Explanation: The L prefix creates a wide string literal, which is displayed using wcout.
Print the Name Entered by the User
Instead of hardcoding the name, the program can read it from the user.
#include <bits/stdc++.h>
using namespace std;
int main() {
// Variable to store the name
string str;
// Taking the name string as input using
// cin object
cin >> str;
// Print the name string using cout object
cout << str;
return 0;
}
Input
AnmolOutput
AnmolExplanation: The name is stored in a string variable using cin and then printed using cout. This allows the program to display any name entered by the user.