CSC115 ยท 2077 ยท 5 marks
What do you mean by unformatted I/O? Explain.
What do you mean by unformatted I/O? Explain. [5]
Quick answer
Unformatted I/O refers to input/output functions in C that read or write data without any format specification. These functions do not require a format string (like %d, %f, etc.) and deal with raw characters or strings directly. They are simpler and faster than formatted I/O functions like scanf() and printf().
Unformatted I/O in C
Definition
Key Characteristics
- No format specifiers are used.
- They work directly with characters and strings.
- They are declared in the header file
<stdio.h>. - They are mainly used for simple character-level or string-level input and output.
Unformatted I/O Functions in C
1. Character Input/Output Functions
| Function | Purpose |
|---|---|
getchar() | Reads a single character from standard input (keyboard) |
putchar() | Writes a single character to standard output (screen) |
Syntax:
char ch;
ch = getchar(); // reads one character
putchar(ch); // prints one character
Example:
#include <stdio.h>
int main() {
char ch;
ch = getchar(); // user types a character
putchar(ch); // prints that character
return 0;
}
2. String Input/Output Functions
| Function | Purpose |
|---|---|
gets() | Reads a string (including spaces) from standard input |
puts() | Writes a string to standard output followed by a newline |
Syntax:
char name[50];
gets(name); // reads a full line as string
puts(name); // prints the string
Example:
#include <stdio.h>
int main() {
char name[50];
gets(name); // reads string with spaces
puts(name); // prints string and moves to new line
return 0;
}
Difference: Unformatted vs Formatted I/O
| Feature | Unformatted I/O | Formatted I/O |
|---|---|---|
| Format specifier | Not required | Required (%d, %f, etc.) |
| Functions | getchar(), putchar(), gets(), puts() | scanf(), printf() |
| Data type handled | Characters and strings only | Any data type |
| Complexity | Simple | More flexible |
Summary
Unformatted I/O functions are used when the program needs to handle raw characters or strings without worrying about data types or format specifiers. They are straightforward, easy to use, and suitable for simple input/output operations in C programs.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.