getchar() in C: Reading Character Input

getchar() reads the next byte from standard input and returns it as an int. Using int is important because the function must also be able to return the special value EOF.

Syntax Top ↑

int ch = getchar();

Read and Display One Character Top ↑

#include <stdio.h>

int main(void) {
    int ch;

    printf("Enter one character: ");
    ch = getchar();

    if (ch == EOF) {
        printf("No input available.\n");
        return 1;
    }

    printf("You entered: %c\n", ch);
    return 0;
}

Use getchar() with a Condition Top ↑

#include <stdio.h>

int main(void) {
    int answer;

    printf("Do you like C programming? Press Y or N: ");
    answer = getchar();

    if (answer == 'Y' || answer == 'y') {
        printf("Keep practicing C.\n");
    } else if (answer == 'N' || answer == 'n') {
        printf("Try smaller examples and practice regularly.\n");
    } else {
        printf("Please enter Y or N.\n");
    }

    return 0;
}

Read Characters Until Enter Is Pressed Top ↑

Key change: keep reading until the newline character or end-of-file is reached.

#include <stdio.h>

int main(void) {
    int ch;

    printf("Enter text: ");

    while ((ch = getchar()) != '\n' && ch != EOF) {
        printf("Read: %c\n", ch);
    }

    return 0;
}

Copy Standard Input to Standard Output Top ↑

#include <stdio.h>

int main(void) {
    int ch;

    while ((ch = getchar()) != EOF) {
        putchar(ch);
    }

    return 0;
}

This classic loop demonstrates why the return value should be stored in an int: a char may not be able to represent every byte value and EOF distinctly.

Preserved Example: Read Until q Is Entered Top ↑

#include <stdio.h>

int main(void) {
    int ch;

    printf("Enter characters (q to quit):\n");
    while ((ch = getchar()) != EOF && ch != 'q') {
        printf("You entered: %c\n", ch);
    }

    return 0;
}

Preserved Example: Pause for Enter Top ↑

#include <stdio.h>

int main(void) {
    printf("Press Enter to continue...\n");
    (void)getchar();
    printf("Program continued.\n");
    return 0;
}




plus2net.com



nurr

10-11-2013

hi,
how i'm going to change this code using string, for example Y change it to YES, and N change it to NO.
thanks for help...
Michael Ziile

22-01-2019

illustrate with examples
a)reading character and string variable
b)writing character and string variable



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer