简单的C程序数字符 - 帮助请 [英] Simple C program to Count Character - Help please

查看:119
本文介绍了简单的C程序数字符 - 帮助请的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我在C写两个方案来算字符和打印的价值,但既不似乎工作。一种使用而循环和另一个使用了,而编译没有错误报告,但既不打印总数。或为此事东西。

Hey, so I've wrote two programs in C to count characters and print the value but neither seem to work. One uses the while loop and the other uses for, no errors are reported while compiling, but neither print the total count. Or anything for that matter.

这里的code。使用的,而的:

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);
}

和使用这里的code的的:

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", nc);
}

双方确定编译并运行。当我输入的输入并回车,空白打印换行符。当我简单地按下没有输入任何内容,回车,再一个空白的新行打印(而且我认为这将至少打印零)。我不知所措,为什么,似乎一切OK ......所以如果你能帮助我在这里我真的AP preciate它。

Both compile ok and run. When I type input and hit enter, a blank newline prints. When I simply hit enter without inputting anything, again a blank newline prints (and I'd think it would at least print zero). I'm at a loss as to why, everything seems ok... so if you could help me out here I'd really appreciate it.

推荐答案

您需要输入终止你的程序(即触发EOF测试)。

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

您可以在大多数Windows命令行窗口新行的起点上大多数UNIX终端用Ctrl-D或Ctrl-Z做到这一点。

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

此外,你应该给主要的返回类型;隐 INT 是德precated。

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

int main(void)

这篇关于简单的C程序数字符 - 帮助请的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆