How to print a string to console in C++

In other languages like C programming, we use the printf function to print a string to the console. In this article, we will discuss how we can print a string to a console in C++.

The “cout” object is used to print output on the console in C++. So we can use it to print strings on the console. First, let’s discuss cout and how we can use it to display a string to the console using it.

cout in C++ :

cout means console output. It’s an object of the output stream class(iostream class). This cout object along with the “<<” operator is used for displaying output on the console. Where “<<” means extraction operator. Next to this operator, we specify the string to be printed. cout is defined in std namespace so we can either use the scope resolution operator each time with cout like this std::cout or we can use “using namespace std;” at the beginning of our program.

Let’s look at the below coding example, in which we will print a string “CodeSpeedy.com” using cout(console output).

#include <iostream>
using namespace std;
int main() {
    string s = "CodeSpeedy.com";
    cout<< s <<endl;
    cout<< "CodeSpeedy.com" <<endl;
    return 0;
}

Or we can write the same code using the scope resolution operator (::) which is generally used to specify to which namespace it belongs. Here cout belongs to the std namespace so we use std::cout in our code. For “endl” also, we do the same.

#include <iostream>

int main() {
    std::string s = "CodeSpeedy.com";
    std::cout<<s<<std::endl;
    std::cout<<"CodeSpeedy.com"<<std::endl;
    return 0;
}

Output : 

CodeSpeedy.com
CodeSpeedy.com

For both codes, we have to include the iostream header file at the beginning of the program. Hope you have understood the entire discussion.

Leave a Reply

Your email address will not be published. Required fields are marked *