Unformatted Input/Output Functions
Unformatted input/output in C involves reading or writing raw data without specific formatting instructions. The data is typically treated as a sequence of bytes. Unformatted I/O functions are useful when working with binary files or dealing with raw data that doesn't have a specific textual representation.The functions getchar(), putchar(), puts(), getch(), getche(), putch() are considered as unformatted functions.
4.2.1. Character I/O:
Following are the standard character I/O functions:
#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
c = getchar();
printf("You entered: ");
putchar(c);
return 0;
}
#include <stdio.h>
int main() {
char c = 'A';
printf("The character is: ");
putchar(c);
return 0;
}
#include <conio.h> // For getch()
int main() {
char c;
printf("Press a key: ");
c = getch();
printf("You pressed: %c\n", c);
return 0;
}
#include <conio.h> // For getche()
int main() {
char c;
printf("Press a key: ");
c = getche();
printf("\nYou pressed: %c\n", c);
return 0;
}
#include <conio.h> // For putch()
int main() {
char c = 'A';
putch('The character is: ');
putch(c);
return 0;
}
4.2.2. String I/O
Following are the standard String I/O functions:
gets(): Reads a line of text from the standard input into a character array until a newline character is encountered. This function is unsafe and is generally not recommended for use because it doesn't perform bounds checking.
#include <stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
gets(str); // Avoid using gets() due to its unsafe nature
printf("You entered: %s\n", str);
return 0;
}
Instead of gets(), it is recommended to use fgets() for safer input:
#include <stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s\n", str);
return 0;
}
puts(): Writes a string (followed by a newline character) to the standard output.
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
puts("This is a string:");
puts(str);
return 0;
}