开发者

How do I enter data in a program to count the entered characters?

开发者 https://www.devze.com 2023-01-08 13:22 出处:网络
I wrote two programs in C to count characters and print the value. One uses the while loop and the other uses for. No errors are reported while compiling, but neither print anything.

I wrote two programs in C to count characters and print the value.

One uses the while loop and the other uses for. No errors are reported while compiling, but neither print anything.

Here's the code using while:

#include <stdio.h>

/* count characters and input using while */
main()
{
    long nc;

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

And here's the code using for:

#include <stdio.h>

/* count characters and input using for */
main()
{
    long nc;

    for (nc = 0; getchar() != EOF; ++nc)
        ;
    printf("%ld\n", 开发者_Python百科nc);
}

Both compile and run.

When I type input and hit enter, a blank newline prints. When I hit enter without inputting anything, again a blank newline prints. I think it should at least print zero.


You need to terminate the input to your program (i.e. trigger the EOF test).

You can do this on most unix terminals with Ctrl-D or Ctrl-Z at the start of a new line on most windows command windows.

Alternately you can redirect stdin from a file, e.g.:

myprogram < test.txt

Also, you should give main a return type; implicit int is deprecated.

int main(void)


Your programs will only output after seeing an end of file (EOF). Generate this on UNIX with CTRL-D or on Windows with CTRL-Z.


You wait for an EOF character (end of file) here. This will only happen in two scenarios:

  • The user presses Ctrl+Break (seems to work on Windows here, but I wouldn't count on this).

  • The user enters a EOF character (can be done with Ctrl+Z for example).

A better way to do this would be to check for a newline instead.


for your program to work correctly. after you press the enter key, u have to ensure that uyou terminate your loop, so that the program flos correctly. this is done by typing the ctrl+Z from your keyboard. these are the keys that correspond to the EOF.


Pressing Enter on your keyboard, adds the character \n to your input. In order to and the program and have it print out the number of characters you would need to add an 'End of File' (EOF) character.

In order to inject an EOF character, you should press CTRL-D in Unix or CTRL-Z on Windows.


You do realize that newline is a normal character, and not an EOF indicator? EOF would be Ctrl-D or Ctrl-Z on most popular OSes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号