Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is printf supposed to print out a 'long' value? [duplicate]

Tags:

c

Possible Duplicate:
Why doesn’t getchar() recognise return as EOF in windows console?

I'm trying to print out the value in the variable 'nc' in the next program:

int main()

{ 
 long nc;
 nc = 0;

 while (getchar() != EOF)
 ++nc;
 printf("%ld\n", nc); 
}

Please tell me why is it not printing?

like image 494
MNY Avatar asked Jan 31 '26 18:01

MNY


2 Answers

You don't have brackets in your while loop (this is why not using brackets leads to error prone software). Therefore, the value is getting incremented, but not printing.

Try:

int main(int argc, char** argv)
{ 
    long nc;
    nc = 0;

    while (getchar() != EOF)
    { // ADD THIS
        ++nc;
        printf("%ld\n", nc); 
    } // AND THIS
}

otherwise, your code is essentially doing:

int main(int argc, char** argv)
{ 
    long nc;
    nc = 0;

    while (getchar() != EOF)
    {
        ++nc; // ENDLESSLY ADDING
    }
    printf("%ld\n", nc); // NEVER REACHED DUE TO WHILE LOOP.
}
like image 107
Inisheer Avatar answered Feb 02 '26 11:02

Inisheer


Your while loop will continue to loop until you end the input using Control-D on Unix or Control-Z, Return on Windows. It will do this without printing anything because you did not use braces around the ++nc and printf.

You may also have problems with printf if you did not #include <stdio.h> at the top of your program. If the compiler does not know that printf is a varargs function, it will not format the argument list correctly when calling it.

like image 41
Zan Lynx Avatar answered Feb 02 '26 09:02

Zan Lynx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!