Multiple word string in C

Introduction

In the previous article, we have seen while taking input from a user the ‘scanf’ function doesn’t take multiple words as input.

Suppose we want the user to enter his full name including first name and last name. Then of course the user is going to add white space between first name and last name. As studied earlier, anything written after white space will be neglected by the compiler. Thus, the compiler will show the first name as output.

Therefore, it is necessary to resolve this issue. The solution is gets and puts function.

Syntax

The syntax of the ‘scanf’ function for taking multiple words as one string is

scanf( “%[^\n]s”, name);’. Since it is a complex syntax so better to use the gets function.

gets and puts Function

For taking input of a string consisting of more than one word, we will use the gets function. Similarly, for giving the output of a string consisting of more than one word, we will use the puts function.

Program

#include<stdio.h>
int main()
{
            char name[20];
            printf("Enter your name:\n");
            gets(name);
            printf("Your name is ");
            puts(name);
}

 

Output

Multi-word string in C

Explanation

Instead of using the ‘scanf’ function we use the gets function and pass the ‘name’ variable in it so that the multiple word sting gets stored in it. puts function print the data which is stored in ‘name’ variable.

Note: ‘printf’ can also be used to print the multi-word string instead of using puts. Try to write the same code with the ‘printf’ function, you will get the same output.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.