rubing Posted February 6, 2009 Share Posted February 6, 2009 I am following along with exercises from a book (C Programming), and one of the examples doesn't seem to be working. I believe it's supposed to print the number of characters you enter, but it doesn't do anything. Is there something wrong with my code? #include <stdio.h> main() { long nc; nc=0; while (getchar() != EOF) ++nc; printf("%ld\n",nc); } Link to comment https://forums.phpfreaks.com/topic/143990-solved-print-of-characters-in-c/ Share on other sites More sharing options...
corbin Posted February 6, 2009 Share Posted February 6, 2009 A book really had that as an example? Weird. #define EOF (-1) Is what stdio.h has for me, and I would assume it is the same with all versions of stdio. That said, when comparing a character to an integer, it compares the numeric equivalent of the character (for example, if the encoding is ASCII, 'a' == 97). No character encoding that I know of uses -1, so entering that wouldn't exactly be possible. Perhaps you could change the code to check for a line break or a period? while(getchar() != '.') for example.... (Single quotes are used because double quotes would make it a null terminated char array. In other words, it would be \2E\00 instead of \2E (hex representation), and of course a single character (as returned from getchar()) will never match a null terminated char array.) Link to comment https://forums.phpfreaks.com/topic/143990-solved-print-of-characters-in-c/#findComment-755613 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.