C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

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:

  • getchar(): Reads a single character from the standard input (usually the keyboard).
#include <stdio.h>

int main() {
    char c;

    printf("Enter a character: ");
    c = getchar();

    printf("You entered: ");
    putchar(c);

    return 0;
}
  • putchar(): Writes a single character to the standard output (usually the console).
#include <stdio.h>

int main() {
    char c = 'A';

    printf("The character is: ");
    putchar(c);

    return 0;
}
  • getch(): Reads a character directly from the console without waiting for the Enter key. (Note: getch() is not a standard C library function and might be platform-dependent. It's often used in old MS-DOS environments.)
#include <conio.h>  // For getch()

int main() {
    char c;

    printf("Press a key: ");
    c = getch();

    printf("You pressed: %c\n", c);

    return 0;
}
  • getche(): Similar to getch(), but echoes the entered character to the console.
#include <conio.h>  // For getche()

int main() {
    char c;

    printf("Press a key: ");
    c = getche();

    printf("\nYou pressed: %c\n", c);

    return 0;
}
  • putch(): Writes a character directly to the console without buffering.
#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;
}