Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
