Is getchar () equivalent to scanf ("% c") and putchar () equivalent to printf ("% c")?

Is a = getchar() equivalent to scanf("%c",&a); ?

Is putchar(a) equivalent to printf("%c",a); where a is a char variable?

+7
c scanf getchar putchar
source share
2 answers

In general, yes, they are the same.

But they are not in a few insignificant ways. The getchar function getchar printed to return int , not char . This is done so that getchar can both all possible char values ​​and error codes.

So, if the following compilation is done on most compilers, you essentially truncate the error message

 char c = getchar(); 

The scanf function, however, allows you to directly use the char type and separates the error code from the return value.

+7
source share

They do the same here. However, if you know that you are just making characters, then getchar and putchar will be more efficient, since the printf and scanf options will have to parse the string each time to determine how to handle your request. In addition, they can be called in a lower-level library, which means that you may not need to link printf / scanf if they are not needed elsewhere.

+1
source share

All Articles