C program to read and print strings

In this tutorial, you will learn and get code for reading and printing strings in the C language using the following methods:

To print any string in C programming, use the printf() function with the format specifier %s, as shown here in the following program. To scan or get any string from the user, you can use either the scanf() or gets() functions. Let's take a look at both functions one by one.

Read and print strings using the scanf() and printf() functions

The question is: write a program in C that allows the user to enter any string (using scanf()) at run-time and print it back on the output screen (using printf()). The answer to this question is:

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[20];
    printf("Enter your first name: ");
    scanf("%s", str);
    printf("Hello, %s", str);
    getch();
    return 0;
}

As the above program was written in the Code::Blocks IDE, here is the output you will see on your screen after a successful build and run:

c program print string

Supply your name, say "codes" as input, and press ENTER to see the output as given in the second snapshot here:

get string input c program

As you can see from the above sample run, we have provided a string without spaces, but what if you want to provide a string with spaces? Before solving the problem, let's understand, with the help of the program given below, how reading the string from the user with the help of the scanf() function has a limitation:

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[100];
    printf("Enter any sentence: ");
    scanf("%s", str);
    printf("\nYou have entered:\n");
    printf("%s", str);
    getch();
    return 0;
}

Here is the sample run:

c program read print string

Now enter any string, say "we love codescracker," and press ENTER. Here is the sample output:

read and print string c program

As you can see from the above sample run, the scanf() function only scans the first word, and all the words after a space are skipped by this function. Therefore, to solve this problem, we have to use the gets() function to get the string input from the user.

Read and print strings using the gets() and puts() functions

Here is a modified version of the above program that takes the whole line as input without caring about spaces:

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[100];
    printf("Enter any sentence: ");
    gets(str);
    printf("\nYou have entered:\n");
    puts(str);
    getch();
    return 0;
}

Here is the first screenshot of the sample run:

read print string c program

Now provide the same input as provided in the above sample run, that is, "we love codescracker," and press ENTER. This time you will see the whole string as output:

c read and print string

The same program in different languages

C Quiz


« Previous Program Next Program »


Liked this post? Share it!