C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Input and display string

C Program: Input and display string

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char str[100];

 

    // Input string

    printf("Enter a string: ");

    gets(str); // Note: gets() is unsafe, use fgets() in practice

 

    // Display string

    printf("You entered: %s\n", str);

 

    return 0;

}

Output

 
INPUT :
Enter a string: Welcome to ITDeveloper.in

OUTPUT :
You entered: Welcome to ITDeveloper.in

Explanation

  1. A character array (str) is declared to store the string.
  2. The program takes input using gets() (which reads input until a newline).
    • In modern C, prefer fgets(str, sizeof(str), stdin) for safety.
  3. The string is then printed using the %s format specifier.

 

C Program: Input and display string

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char str[100];

 

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin); // safer alternative to gets()

 

    printf("You entered: %s", str);

    return 0;

}

Output

 
INPUT :
Enter a string: Welcome to ITDeveloper.in

OUTPUT :
You entered: Welcome to ITDeveloper.in

Explanation

  1. A character array (str) is declared to store the string.
  2. The program takes input using gets() (which reads input until a newline).
    • In modern C, prefer fgets(str, sizeof(str), stdin) for safety.
  3. The string is then printed using the %s format specifier.