C Program to take string as an input

Category: C ProgramTags: 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

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);
}

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);
}

String input using gets() function

#include <stdio.h>

void main()
{
  char str[50];

  printf("Enter the string: ");
  scanf("%[^\n]c", str);

  printf("%s", str);
}

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

Output

Enter the string: procoding
procoding