C Programming (Beginner help) relating to getchar() putchar()
-
10-06-2021 - |
Frage
Im new to C programming and wanted to clear, what may seem to be, a silly doubt...
Code:
#define EOF 0
main()
{
int c;
c=getchar();
while (c!= EOF)
{
putchar (c);
c= getchar();
}
}
this should just return the value I enter...but accordingly...shouldnt it terminate when I enter 0? If not...what exactly does the statement under 'while' signify? Any help would be greatly appreciated guys :)
Lösung
The getchar
function returns the ASCII value entered (48 for zero, or '0'
), or a value called EOF
in the header file <stdio.h>
(normally -1).
So if you want to stop either on EOF (the proper EOF, not the one you defined) or if the user writes a zero, then this will work much better:
#include <stdio.h>
int main()
{
int c = getchar();
while (c != EOF && c != '0')
{
putchar(c);
c = getchar();
}
return 0;
}
Andere Tipps
EOF
means when you hit, for instance, ctrl + d
in linux, it sends EOF
signal, it's not necessarily a 0
.
EOF
is certainly not 0
(nor is it '0'
, the char literal equaling 48). It's not char
at all. stdio.h
(which you should be #include
-ing!) defines it as -1
. It indicates that whatever file you are reading has no more data in it. It's not a byte in the stream, rather the way that the io library indicates that it has finished.
The whole reason getchar
needs to return an int
is so that the end-of-file indicator cannot possibly be a valid byte in the file.
Other functions indicate that the EOF has been reached differently: fgets()
returns NULL
. read()
which returns the number of bytes read returns 0, indicating that it could read nothing.
When you enter a 0
, it's not actually a zero, just the ASCII character 0
. It has a numerical value of 48, which can be verified by printf("%d\n", '0');
, which prints 48. An EOF
is an actual zero, that is, it's representation is essentially zero.