Search code examples
cgetcharputchar

Very simple C question using getchar() and putchar()


Hello I am teaching myself C and going through the K & R book and I am having some trouble (I am running OS X). This is from section 1.5.1 "File Copying" which is supposed to take a character as input, then output the character. Here is the code:

#include <stdio.h>

/* --  Copy input to output -- */ 
int main(void)
{
int c;

c = getchar();

while ( c != EOF ) {
    putchar(c);
    c = getchar;
}


}

So, I think my problem is not with the code itself but with compling and running. First of all, when compiling I get the following errors

/Volumes/Goliath/Dropbox/C programs/prog1_5_1.c: In function ‘main’:
/Volumes/Goliath/Dropbox/C programs/prog1_5_1.c:12: warning: assignment makes integer from pointer without a        cast
/Volumes/Goliath/Dropbox/C programs/prog1_5_1.c:16: warning: control reaches end of non-void function

Then when I run the output file (in terminal) it has a small space, then when I input a letter, say I type

a

then I hit Return

and I get a new line. If I then hit a new key, the screen starts going crazy with question marks all over the place.

I am not sure if I am making much sense but I am finding this an odd problem to have. Thank you very much in advance


Solution

  • The second assignment should be c = getchar();. By leaving out the parentheses, you're assigning the address of the getchar function to c, which is very much not what you want.

    Also, at the end of main you need the line return 0; or similar in order to get rid of the "control reaches end of non-void function" warning.