简体   繁体   English

程序似乎跳过了 getchar()

[英]Program seems to skip getchar()

So I'm new to coding in C and coding in general.所以我是 C 语言编码和一般编码的新手。 I'm learning with a book and a code in there just won't work and I don't know why.我正在学习一本书,里面的代码不起作用,我不知道为什么。 It's probably a trivial matter but as I said..I'm a bloody noob.这可能是一件小事,但正如我所说的......我是一个该死的菜鸟。 Anyway this is the code:无论如何,这是代码:

#include <stdio.h>

void main()
{
    char a, b;
    
    printf("Welches Zeichen ist groesser?");
    printf("\nGeben Sie ein Zeichen ein:");
    a = getchar();
    printf("Nun ein anderes Zeichen:");
    fflush(stdin);
    b = getchar();
    
    if( a > b)
    {
        printf("'%c' ist groesser als '%c'!\n", a, b);
    }
    else if( b > a)
    {
        printf("\n'%c' ist groesser als '%c'!\n", b, a);
    }
    else
    {
    printf("\nBitte nicht zweimal das gleiche Zeichen eingeben!");
    }
}

I don't get any compiler error messages, it just seems to 'skip' the second getchar and go straight to the last printf.我没有收到任何编译器错误消息,它似乎只是“跳过”第二个 getchar 并直接转到最后一个 printf。 I feel like it has something to do with fflush(stdin).我觉得它与 fflush(stdin) 有关。 It doesn't matter if it's in the code or not.它是否在代码中并不重要。 I already tried fflush(stdout) but with the same outcome.我已经尝试过 fflush(stdout) 但结果相同。 Can somebody tell me why and please don't be too harsh.谁能告诉我为什么,请不要太苛刻。 Thanks in advance!提前致谢!

As pointed out before fflush() is only for output streams, not input.正如之前指出的 fflush() 仅用于输出流,而不是输入。

To read different lines fgets() might be attractive to you.阅读不同的行 fgets() 可能对您有吸引力。 No fflush() required.不需要 fflush()。

If you can get hold of the ANSI final draft of the early C standard it has two sections, the specification and a "rationale" saying why some choices were made.如果你能拿到早期 C 标准的 ANSI 最终草案,它有两部分,规范和说明为什么做出某些选择的“基本原理”。 It really helped me learn C in the days.它真的帮助我在这些日子里学习了 C。 Now days I download and save an ISO final draft to see where C is now.现在,我下载并保存 ISO 最终草案以查看 C 现在的位置。

7.21.5.2 The fflush function 7.21.5.2 fflush 函数

Synopsis概要

#include <stdio.h> int fflush(FILE *stream); #include <stdio.h> int fflush(FILE *stream);

Description If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file;描述 如果 stream 指向一个输出流或一个更新流,其中最近的操作没有输入,fflush 函数会导致该流的任何未写入数据被传递到主机环境以写入文件; otherwise, the behavior is undefined.否则,行为未定义。

If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above如果流是空指针,则 fflush 函数对上面定义了行为的所有流执行此刷新操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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