[sclug] Off topic C question

Simon Heywood simon at triv.org.uk
Fri Sep 22 10:31:21 UTC 2006


On Fri, 22 Sep 2006 11:11:32 +0100, Patrick wrote:
> Can anyone see why this character counting program always finds zero 
> characters?  Its based on an example from K&R Chapter 1 which also fails.

It doesn't even compile for me, so I've no idea how you managed to run
it. You might also want to turn on / check compiler warnings.

> #include "stdio.h"

It's a system header, so it should be '#include <stdio.h>'.

> int main()
> {
>         /* count characters*/
>         FILE *inFile;
>         inFile = fopen("motd.xml", "r");
>         int c = 0;
>         long lc = 0;
> 
>         while ((c = getc(inFile)) != EOF)
>         {
>                 if (c == "l") {

This is wrong. You're comparing an int (the byte returned by getc())
with a pointer to char ("1"). What are you trying to do?

>                 ++lc;
>                 }
> 
> 
>         }
> 
>         printf("Typed %1d lines\n", nc);

s/nc/lc/

> 
>         system("pause");
>         return 0;
> 
> }

HTH,
S.


More information about the Sclug mailing list