std::getchar(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::getchar(3) πŸ’–

okay so welcome to the std::getchar(3) page from the C++ Standard Libary (that's the manual name, and yes it's spelled that way in the original β€” not me, bestie πŸ’…). This is the std::getchar page, and she's lowkey a whole main character.

🌸 NAME 🌸

std::getchar - std::getchar. That's it. That's the name. The algorithm is: be named exactly that. Periodt. πŸ’…

✨ Synopsis ✨

Defined in header <cstdio>:

int getchar();

Reads the next character from stdin.

Equivalent to std::getc(stdin). She's literally std::getc with stdin locked in β€” no cap. 🫢

πŸŽ€ Parameters πŸŽ€

  • (none) β€” not a single parameter. She takes zero arguments and still eats.

πŸ¦‹ Return value πŸ¦‹

  • Success: the obtained character.
  • Failure: EOF.

If the failure has been caused by end of file condition, additionally sets the eof indicator (see std::feof()) on stdin. If the failure has been caused by some other error, sets the error indicator (see std::ferror()) on stdin.

πŸ”₯ Example πŸ”₯

std::getchar with error checking. Exit program by entering ESC char. Here's the whole vibe:

#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>

int main()
{
    for (int ch; (ch = std::getchar()) != EOF ;) // read/print "abc" from stdin
    {
        if (std::isprint(ch))
            std::cout << static_cast<char>(ch) << '\n';
        if (ch == 27) // 'ESC' (escape) in ASCII
            return EXIT_SUCCESS;
    }

    // Test reason for reaching EOF.
    if (std::feof(stdin)) // if failure caused by end-of-file condition
        std::cout << "End of file reached\n";
    else if (std::ferror(stdin)) // if failure caused by some other error
    {
        std::perror("getchar()");
        std::cerr << "getchar() failed in file " << std::quoted(__FILE__)
                  << " at line # " << __LINE__ - 14 << '\n';
        std::exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}

🌈 Possible output 🌈

abc
a
b
c
^[

That last line? That's the ESC char moment β€” iconic, honestly. πŸ’€

πŸ” See also πŸ”

  • fgetc β€” gets a character from a file stream
  • getc β€” (function)
  • C documentation for getchar β€” the C docs for getchar

okay that's the whole page! source/version: http://cppreference.com Β· date: 2024.06.10 Β· page: std::getchar(3) β€” love u, bestie, go read some chars πŸ’–βœ¨

πŸ“¦ where this page comes from