Search code examples
c++cgetchar

What is the use of getchar()?


Where do we use getchar() instead of scanf() or cin ? Also, shouldn't the syntax of getchar() be char getchar() instead of int getchar()? Since we are reading in character type input.


Solution

  • C and C++ are different languages; getchar exists in C whereas cin (which inherently depends on classes) does not. Also scanf is very slow compared to getchar because scanf has to read through a lot more data and do a lot more processing than getchar does.

    Another reason for having getchar is that it is used in while loops like this

    int c;
    while ((c = getchar()) != EOF) {
      /* do some stuff here */
    }
    

    so that you can keep reading characters until you specifically reach EOF (or any other character you choose).

    By the way, EOF is an int (because it isn't a valid character that can be read) which is why getchar has to return an int.