codescracker
c++

C++ Program to Print String



« Previous Program Next Program »

In this article, you will learn and get code to print string in C++ language. Here are the list of programs on printing of string entered by user at run-time:

Print String in C++

To print a string in C++ programming, first ask from user to enter any string, to 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 give below. Let's first create a program that uses cin:

To print the string, just place the string (variable that stores 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 build and run under Code::Blocks IDE. Here is its sample run:

C++ program print string

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

print string c++

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

Here is another example program on printing of a string entered by user, using gets() function:

#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;
}

Following is its sample run with user input, this is codescracker:

c++ print string

To learn more about, receiving string input from user, refer to get input from user article to get every required things.

Print String using Pointer

This program does the same job as of previous program, that is printing of a string. The only difference is, this program uses pointer 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 above program, a pointer type variable say ptr gets declared of same type, that is char. And the address of character at very first index of string, gets initialized to ptr. Now using pointer-type variable named ptr, we have scanned and printed the string, in character-by-character manner.

Note - The * is called as value at operator. Whereas & is called as address of operator.

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

Same Program in Other Languages

C++ Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker