codescracker
c

C Program to Read and Print String



« Previous Program Next Program »

In this tutorial, you will learn and gets code about reading and printing string in C language using following ways:

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

Using scanf() and printf() Function

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

// Read and Print String using scanf() and printf()
// ----codescracker.com----

#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 under Code::Blocks IDE, therefore here is the output you will see on your screen after 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 space, but what if you want to provide a string with space. Before solving the problem, let's understand with the program given below, that how reading the string from user with the help of scanf() function has a limitation:

// ----codescracker.com----

#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, scanf() function only scans the first word, and all the words after space gets skipped by this function. Therefore to solve this problem, we have to use gets() function function to get the string input from user.

Using gets() and puts() Function

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

// ----codescracker.com----

#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 watch the whole string as output:

c read and print string

Same Program in Other Languages


« Previous Program Next Program »