【问题标题】:Input does not exit in c, thus output does not work输入在c中不退出,因此输出不起作用
【发布时间】:2016-10-22 00:36:50
【问题描述】:

我刚学c,我用的是Linux终端。我编写了以下简单代码,但是当我输入输入时,文件不会退出,因此不计算字符数。任何人都可以帮我吗?我也尝试过其他输入代码。我所有的输入相关代码都是一样的。我究竟做错了什么?请帮忙。

main()
{    
    /* count characters in input */    
    printf("Type some characters and the program will count the number of characters: ");

    int c = getchar();

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

    printf("Number of characters typed: %1d\n", c);    
}

【问题讨论】:

  • 您只能读取一个字符,因为您只调用一次getchar。只要不遇到EOF(或\n或任何你的停止条件,可能是while ((c=getchar()) != EOF)
  • 这个 getchar() 函数是什么?获取输入的方式通常是通过 scanf("%s", buffer) 获取输入并将其复制到变量 buffer
  • @Yvain getchar 是 stdio.h 中定义的标准函数;如果 OP 想通过 char scanf("%s") 读取 char 是不合适的。
  • 您还使用与输入字符相同的变量来计算字符数。这怎么可能行得通?
  • 感谢您指出愚蠢的错误@Barmar。我快疯了!毕竟是周五晚上!更新代码:#include main() { int c; printf("请输入一些字符:"); while(getchar()!=EOF && getchar()!= '\n') ++c; printf("输入的总字符数= %1d \n", c); }

标签: c input output eof


【解决方案1】:

所以要注意有用的 cmets;

#include <stdio.h>

int main(){
        int c;
        int count = 0;

        while((c=getchar()) != '\n' && c != EOF)
                count++;
        printf("%d\n", count);
};

此代码按预期工作。

【讨论】:

  • 你是说while((c=getchar()) != '\n' || c != EOF)应该用吗?这不是一个无限循环,因为所有字符,甚至'\n'EOF 都不等于任何一个,并且会使条件始终为true
  • 不,这个循环的意思是:“只要输入的字符 既不 'newline' 也不 'EOF'”,如果你替换或和它的意思是“只要输入不是'换行'结合与'EOF'”,所以这个永远不会停止。
  • 你搞错了伙计。假设c'\n'。您的条件将评估为while('\n' != '\n' || '\n' != EOF) ===> while(false || true) ===> while(true)。现在让我们看看c 是不是EOFwhile(EOF != '\n' || EOF != EOF) ===> while(true || false) ===> while(true)。对于其他一切while(true || true)。循环什么时候结束?我不敢相信我必须在这里输入代码的评估。
猜你喜欢
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多