C Program to take string as an input
Category: C Program
Tags: #cprogram#string
Write a C Program to take a string as input from the user. Basically, we use four methods to take input from the user. 1. Using scanf with %s format specifier 2. Using scanf with %c format specifier 3. Using gets function 4. Using fgets function
1. String input using scanf()
and %s
format specifier
#include <stdio.h>
void main()
{
char str[50];
printf("Enter the string: ");
scanf("%s", str);
printf("%s\n", str);
}
2. String input using scanf()
and %c
format specifier
#include <stdio.h>
void main()
{
char str[50];
printf("Enter the string: ");
scanf("%[^\n]c", str);
printf("%s", str);
}
3. String input using gets()
function
#include <stdio.h>
void main()
{
char str[50];
printf("Enter the string: ");
scanf("%[^\n]c", str);
printf("%s", str);
}
4. String input using fgets()
function
#include <stdio.h>
void main()
{
char str[30];
printf("Enter the string: ");
fgets(str, sizeof(str), stdin);
printf("%s", str);
}
Output
Enter the string: procoding
procoding