Learning Input Methods in C

Table of contents
Challenge:
You need to read and print a character, a word (string), and a sentence (with spaces) in C. Each input type must be handled correctly and output in the required format.
Solution:
#include <stdio.h>
int main() {
// Declare variables for character, string (word), and sentence
char c;
char s[100]; // To hold a string (word)
char s2[100]; // To hold a sentence (with spaces)
// Read and print the character
scanf("%c", &c);
printf("%c\n", c);
// Read and print the string (single word without spaces)
scanf("%s", s);
printf("%s\n", s);
// Clear the input buffer before reading the sentence
getchar(); // This consumes the newline character left by the previous scanf
// Read and print the full sentence (including spaces)
scanf("%[^\n]", s2);
printf("%s\n", s2);
return 0;
}
Explanation:
Declaring Variables:
char c;
: to store a single character.char s[100];
: to store a word (up to 99 characters and a null terminator).char s2[100];
: to store a sentence (including spaces).
Reading and Printing a Character:
scanf("%c", &c);
: reads a single character.printf("%c\n", c);
: prints the character.
Reading and Printing a Word:
scanf("%s", s);
: reads a single word (without spaces).printf("%s\n", s);
: prints the word.
Clearing the Input Buffer:
getchar();
: consumes the newline character left by the previousscanf
.
Reading and Printing a Sentence:
scanf("%[^\n]", s2);
: reads a full sentence until a newline is encountered.printf("%s\n", s2);
: prints the sentence.
What I Learned:
Handling Different Input Types in C:
Character input:
scanf("%c", &c)
reads a single character.String input (word):
scanf("%s", s)
reads a single word, but not spaces.Sentence input:
scanf("%[^\n]", s2)
reads until a newline, allowing spaces.
Managing Input Buffers:
- The
getchar()
function helps consume leftover newline characters after reading input, preventing input issues when reading different types.
- The
Understanding and Debugging:
- Input behavior can vary with different
scanf
specifiers. For example,scanf("%[^\n]%*c", s2)
was problematic, but clearing the buffer withgetchar()
resolved the issue.
- Input behavior can vary with different
Key Takeaways:
Always be aware of how input is buffered when using
scanf
.Use
getchar()
to clear newline characters from the input buffer for smooth multiple input reads.Different
scanf
specifiers (%c
,%s
,%[^\n]
) serve specific purposes, and understanding these differences is crucial for writing effective input-handling code in C.
Subscribe to my newsletter
Read articles from Sarthak Kulkarni directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
