Summary: This C program demonstrates how to read a character, a word (string without spaces), and a full sentence (including spaces) from user input using different formats of scanf()
.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char ch;
char s[100];
char sentence[100];
// Read a single character
scanf("%c", &ch);
// Read a string (until whitespace)
scanf("%s", s);
// Consume the leftover newline character before reading the sentence
scanf("\n");
// Read a sentence (until newline)
scanf("%[^\n]", sentence);
// Print outputs as required
printf("%c\n", ch);
printf("%s\n", s);
printf("%s\n", sentence);
return 0;
}
Character Input:
scanf("%c", &ch)
reads a single character including whitespace (e.g., newline), which is why it must be placed first or carefully handled.
String Input:
scanf("%s", s)
reads a string without spaces (stops at the first whitespace character).
Consuming Newline:
scanf("\n")
consumes the leftover newline character in the input buffer from the previous scanf()
call to prevent it from affecting the next input.
Sentence Input:
scanf("%[^\n]", sentence)
reads the rest of the line including spaces until a newline character is found.
Output:
Each input is printed on a new line using printf()
to verify successful reading and format consistency.