简体   繁体   中英

simple C program, printf not printing

I'm new here , asking questions at least. Always have been able to find good answers here. Trying to get back into programming and relearning C but ran into weird issue.

#include <stdio.h>

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

When I run it, after I type in any amount of characters and hit enter, it does not print the value of nc. After hitting enter, I can start typing again and well, same story. Really can't see what could be wrong. The only way it works is if I place both ++nc and the printf within brackets. But then when I hit enter, it gives the value 1-to-nc, which is not what I want. I just want nc. Needless to say the type is not the issue either. Thanks in advance

Type Ctrl-D in your terminal to send EOF . You may want

while (getchar() != '\n')

instead if you want it to work with enter.

您需要按Ctrl-D才能获得EOF。

try

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

Edit : Assuming the input taken from console, '\\n' suffices.

If you just want to get nc printed inside the loop, you should include the print statement in the loop like so:

#include <stdio.h>

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

That prints nc once for each character after hitting [enter], maybe not what you want.

If you want to print nc once per line use scanf and do:

#include <stdio.h>
#include <string.h>

main()
{
    long nc;
    nc = 0;
    char buf[128];
    while (scanf("%s",&buf) > 0) {
      int len = strlen(buf);
      nc += len;
      printf("%ld \n", nc);
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM