C++ getchar()

getchar() prototype

int getchar();

The getchar() function is equivalent to a call to getc(stdin). It reads the next character from stdin which is usually the keyboard.

It is defined in <cstdio> header file.

getchar() Parameters

None.

getchar() Return value

  • On success, the getchar() function returns the entered character.
  • On failure, it returns EOF.
    • If the failure is caused due to end of file condition, it sets the eof indicator on stdin.
    • If the failure is caused by some other error, it sets the error indicator on stdin.

Example: How getchar() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int c,i=0;
    char str[100];
    
    cout << "Enter characters, Press Enter to stop\n";
    
    do
    {
        c = getchar();
        str[i] = c;
        i++;
    } while(c!='\n');
    
    cout << str;
    return 0;
}

When you run the program, a possible output will be:

Enter characters, Press Enter to stop
rtq paSd12 6.2 haQ
rtq paSd12 6.2 haQ

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges