0

My code does not return any value. Can anyone help me explain why it does not work?

#include<stdio.h>

int main()
{
    int nc;
    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%1d\n", nc);
}
J...S
  • 5,079
  • 1
  • 20
  • 35
Bill Cao
  • 1
  • 1

2 Answers2

1

You have to input EOF to get out of the loop.

Windows: Ctrl+Z

Linux : Ctrl+D

See C : How to simulate an EOF?

Only after getchar() returns EOF will the value of nc be printed.

And %1d is effectively same as %d as a number has at least one digit.

If you do %10d or something the number would be printed occupying the space that would've been occupied by a 10 digit number. Default alignment is right. You can make it left aligned with %-10d

J...S
  • 5,079
  • 1
  • 20
  • 35
  • I used Ctrl + Z in my Mac OS terminal console and it seems it only helped to terminate the while loop but it did not return any count value. – Bill Cao Jan 24 '18 at 05:57
  • Yes, I just tried it. I inputed "okay"\n "y", it returns 6D, what does it mean? – Bill Cao Jan 24 '18 at 06:10
  • If I just input "y", then it will return 1D. Does the program just count the the total of characters in an input string plus all the n\? – Bill Cao Jan 24 '18 at 06:11
  • @BillCao Is it not what you wanted to do? – J...S Jan 24 '18 at 06:12
  • @BillCao: Using control-Z on a Unix box suspends the process; it does not terminate the process. It is still running, but in suspended animation until you type a magic incantation at the shell (`fg %1`, for example). – Jonathan Leffler Jan 24 '18 at 06:47
0

I think you're missing the input when you run the code. You have to type in the console after compilation is done. Right now it's not getting any input character to count.

The same code works for me. You can check the below ideone screenshot where same code is returning the correct output . enter image description here

Praful Jha
  • 187
  • 4
  • 18