C++ program to print strings

In this article, you will learn and get code to print strings in the C++ language. The following programs print strings entered by users at run-time:

C++ Print String

To print a string in C++ programming, first ask the user to enter any string and then receive and store the string value in a variable, say str, using cin, gets(), or getline(). And then print the string back on the output screen, as shown in the program given below. Let's first create a program that uses cin:

To print the string, just place the string (the variable that stores the string's value) after cout<<, as shown here in the following program.

#include<iostream>
using namespace std;
int main()
{
    char str[20];
    cout<<"Enter Your First Name: ";
    cin>>str;
    cout<<"\nHello, "<<str;
    cout<<endl;
    return 0;
}

This program was built and runs under the Code::Blocks IDE. Here is its sample run:

C++ program print string

Now supply the string "codescracker" as your first name and press the ENTER key to print the string back on the output screen as shown in the snapshot given below:

print string c++

Note: To receive a string with spaces, use gets() of stdio.h instead of cin.

Here's another example program that uses the gets() function to print a string entered by the user:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char str[200];
    cout<<"Enter the String: ";
    gets(str);
    cout<<"\nYou've entered: "<<str;
    cout<<endl;
    return 0;
}

Here is a sample run with user input, this is codescracker:

c++ print string

To learn more about receiving string input from the user, please see the Get Input from the User article.

Using a pointer, print a string

This program performs the same function as the previous program, which printed a string. The only difference is that this program uses pointers to do the same task.

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char str[200], *ptr;
    cout<<"Enter any String: ";
    gets(str);
    ptr = &str[0];
    cout<<"\nYou've entered: ";
    while(*ptr)
    {
        cout<<*ptr;
        ptr++;
    }
    cout<<endl;
    return 0;
}

The snapshot given below shows the sample run of this program with user input; this is codescracker.com:

print string using pointer

In the above program, a pointer type variable, say ptr, gets declared of the same type, that is, char. And the address of the character at the very first index of the string gets initialized to ptr. Now, using a pointer-type variable named ptr, we have scanned and printed the string in a character-by-character manner.

Note: The * is called as the value at operator, where & is called as the address of operator.

Here, ptr++ means pointer ptr now holds the next index's address.

The same program in different languages

C++ Quiz


« Previous Program Next Program »


Liked this post? Share it!