counting characters in the input with while loop

1.8k views Asked by At

I wrote a simple c program to count number of characters

#include <stdio.h>
main()
{
    long nc;
    nc = 0;

    while (getchar() != EOF)
      ++nc;

    printf("%ld\n", nc);
}

This program is not printing me the characters. On testing different cases, I found that I am stuck in an infinite while() loop.

4

There are 4 answers

0
bilcy On BEST ANSWER
while (getchar() != '\n')
   ++nc;
printf("%ld \n",nc);

Worked!

0
Sourav Ghosh On

This program isn't printing me the characters

It won't. You did not add any statement to print them.

I found that i'm stuck in an infinite while loop

If you don't hit the breaking condition, you'll be in the loop. You need to get EOF to exit the loop. use

  • CTRL+Z (on windows)
  • CTRL+D (on linux)

Now, the solutions:

  1. getchar() won't print the values. You have to store the values and print explicitly (if you want to) using , maybe putchar().

  2. You either supply EOF or change the breaking condition of while() to come out of the essential infinite loop otherwise.


Apart from the coding issues, you need to think about the logic, too. In the present form of the code, getchar() counts the newline (\n) as a valid character, too. To explain, an input in the form of

$ ./a.out  ENTER
a      ENTER
s      ENTER
d      ENTER
f       ENTER
g      ENTER
CTRL+D

Will produce a result

10

but that is not what we generally call counting the character. You may want to review this part of the logic, too.

That said, the recommended signature of main() is int main(void).

4
Vlad from Moscow On

Try the following

#include <stdio.h>

int main( void )
{
    int c;
    long nc = 0;

    while ( ( c = getchar() ) != EOF && c != '\n' ) ++nc;

    printf( "%ld\n", nc );
}

You have to generate the EOF state ( Ctrl+d in UNIX-systems or CTRL+z in Windows) or simply press Enter.

1
Rahul Tripathi On

Try like this:

#include <stdio.h>

int main(void)
{
    int c;
    long nc = 0;

    while ( ( c = getchar() ) != EOF && c != '\n' ) 
    ++nc;

    printf( "%ld\n", nc );
}