Counting characters in input with while loop

I wrote a simple c program to count the number of characters

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

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

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

      

This program does not print characters for me. While testing various cases, I found myself stuck in an infinite loop while()

.

+3


source to share


4 answers


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

      



We worked!

+2


source


This program does not print characters for me

This is not true. You have not added any instructions for printing them. In the meantime, there is no need to worry about it.

I found myself stuck in an endless loop

If you don't get into a hacked state, you will find yourself in a loop. To get out of the loop, you must receive EOF

. use

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

Now the solutions:

  • getchar()

    will not print values. You should store the values ​​and print explicitly (if you like), perhaps putchar()

    .

  • You either supply EOF

    or change the interrupt condition while()

    to break out of the main infinite loop.




Besides coding problems, you also need to think about logic. In this form of code, getchar()

it is also considered a newline character ( \n

) as a valid character. To explain, input in the form

$. / a.out   ENTER
      ENTER
s       ENTER
d       ENTER
e       ENTER
r       ENTER
CTRL+D

There will be a result

ten

but this is not what we usually call character counting. You can also view this piece of logic.

However, the recommended signature main()

is int main(void)

.

+7


source


Try to run

#include <stdio.h>

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

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

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

      

You must generate an EOF state (Ctrl + d on UNIX systems or CTRL + z on Windows) or just press Enter.

+5


source


Try it like this:

#include <stdio.h>

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

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

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

      

+2


source







All Articles