Header Ads Widget

How to take input a string in c

In C programing a string is define as a sequence of character terminated by a null character written  as '\0'.In C language string are represented and store of character array where each element of the character array. store a single character of the string (In sequence). 

There are many way by which we can take input of a string:-

1) scanf("%s",string_name):-

              the drawback of the %s is it take input until space(' ') is encountered,

Code:-

#include<stdio.h>
#include<string.h>
int main()
{
char bin[100];
int word=0;
printf("Enter a sentence\n");
scanf("%s",bin);
printf("The output is:-\n");
puts(bin);
return 0;
}

Output:-

Enter a sentence
This is EasyCodingZone
The output is:-
This


2)  scanf("%[^\n]",string_name):-

Code:-

#include<stdio.h>
#include<string.h>
int main()
{
char bin[100];
int word=0;
printf("Enter a sentence\n");
scanf("%[^\n]",bin);
printf("The output is:-\n");
puts(bin);
return 0;
}

Output:-

Enter a sentence
This is EasyCodingZone
The output is:-
This is EasyCodingZone

3) gets(string_name):-

Code:-

#include<stdio.h>
#include<string.h>
int main()
{
char bin[100];
int word=0;
printf("Enter a sentence\n");
gets(bin);
printf("The output is:-\n");
puts(bin);
return 0;
}

Output:-

Enter a sentence
This is EasyCodingZone
The output is:-
This is EasyCodingZone

4) fgets(string_name,string_max_size,stdin):-

Code:-

#include<stdio.h>
#include<string.h>
int main()
{
char bin[100];
int word=0;
printf("Enter a sentence\n");
fgets(bin,100,stdin);
printf("The output is:-\n");
puts(bin);
return 0;
}

Output:-

Enter a sentence
This is EasyCodingZone
The output is:-
This is EasyCodingZone

Recommended Post:

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-