C Program to read and write character string and sentence

In C programming, reading different types of input requires different functions. Reading a single character uses scanf() with %c, strings without spaces use scanf() with %s, and sentences with spaces require fgets() for proper handling.

Syntax

// Character input
scanf("%c", &character);

// String input (no spaces)
scanf("%s", string);

// Sentence input (with spaces)
fgets(sentence, size, stdin);

Example

This program demonstrates reading a character, string, and sentence from user input −

#include <stdio.h>

int main() {
    char character;
    char string[500];
    char sentence[500];
    
    printf("Enter a character: ");
    scanf("%c", &character);
    
    printf("Enter a string (no spaces): ");
    scanf("%s", string);
    
    // Clear input buffer before fgets
    while (getchar() != '<br>');
    
    printf("Enter a sentence (with spaces): ");
    fgets(sentence, 500, stdin);
    
    // Remove newline from fgets if present
    int len = 0;
    while (sentence[len] != '\0') len++;
    if (len > 0 && sentence[len-1] == '<br>') {
        sentence[len-1] = '\0';
    }
    
    printf("Your character: %c<br>", character);
    printf("Your string: %s<br>", string);
    printf("Your sentence: %s<br>", sentence);
    
    return 0;
}
Enter a character: T
Enter a string (no spaces): ProgrammingLanguage
Enter a sentence (with spaces): I love programming through C
Your character: T
Your string: ProgrammingLanguage
Your sentence: I love programming through C

Key Points

  • Buffer clearing: Use while (getchar() != '
    ');
    instead of fflush(stdin) as it's more portable.
  • fgets() behavior: Includes the newline character in the string, which often needs removal.
  • String arrays: Declare with sufficient size to prevent buffer overflow.
  • Input order: Character and string inputs should come before fgets() to avoid input mixing issues.

Conclusion

Reading different input types in C requires careful handling of input buffers and choosing appropriate functions. Use scanf() for simple inputs and fgets() for strings containing spaces.

Updated on: 2026-03-15T14:21:52+05:30

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements