Search code examples
cwhile-loopgetcharputchar

C Programming (Beginner help) relating to getchar() putchar()


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 :)


Solution

  • 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;
    }