I am using Ubuntu 12.04 LTS with gcc. Can anyone tell me, how can this character type variable hold more than one byte? NOTE : This program will echo all characters(more than one) you type. For instance, if u type "thilip", then it will echo as "thilip". each character holds 8-bits(one byte), so i have typed 6 character (6 bytes). Then, How can getchar function assign this value to character type variable which can hold only one byte?
#include <stdio.h>
int main(void)
{
char ch;
while ((ch = getchar()) != '#')
putchar(ch);
return 0;
}
char
type variable is of 1 Byte. You can check it by
printf("%zu", sizeof(char));
If you are wondering that on giving input
asdf
it is printing
asdf
because of ch
holds this asdf
then you are wrong. getchar()
reads only one character at a time.
When you input multiple char
's then this set of character gets stored in input buffer. Then, getchar()
reads a character one by one from this input buffer and assign one character at a time to the char
variable ch
, and putchar()
prints it one by one. After each iteration ch
is overwritten by the new character read by getchar()
.
You can check that getchar()
reads only one char
at a time by running this code
#include <stdio.h>
int main(void)
{
char ch;
ch = getchar();
putchar(ch);
return 0;
}
Input:
thilip
Output:
t
getchar()
returns int
. You should declare ch
as int
.