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

2

7

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

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

Bacciferous answered 20/3, 2010 at 10:26 Comment(1)
Also see #2507582Appendage
P
8

Generally speaking yes they are the same.

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

So while the following happily compiles in most compilers you are essentially truncating away an error message

char c = getchar();

The function scanf, though, allows you to use a char type directly and separates out the error code into the return value.

Pompano answered 20/3, 2010 at 10:33 Comment(1)
Not error messages (as in, plural), "only" EOF. But otherwise, this is correct. It should also be said that getchar() is much more efficient than scanf(), because the library doesn't have to parse the format string (and the linker doesn't have to link in the large block of code that is scanf()).Martyrdom
Y
1

They do the same thing here. However, if you know you are just doing characters then getchar and putchar will be more efficient, since the printf and scanf variants will have to parse the string each time to determine how to process your request. Plus, they may be called in a lower level library meaning you may not have to have the printf/scanf linked if they are not needed elsewhere.

Yap answered 20/3, 2010 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.