简体   繁体   English

启动C程序时出现问题

[英]Problems Starting C Programs

I'm trying to execute the code below. 我正在尝试执行以下代码。 However, in eclispe, the program doesn't start until I enter a character and press enter. 但是,在eclispe中,该程序直到我输入一个字符并按Enter才启动。 For instance, if I hit run, I have to enter the number that will represent the age before it even asks me to enter my age. 例如,如果我点击“跑步”,则在要求我输入年龄之前,我必须输入代表年龄的数字。 I am wondering how to fix this. 我想知道如何解决此问题。

int main() {

        int age;                          /* Need a variable... */

        printf( "Please enter your age" );  /* Asks for age */
        scanf( "%d", &age );                 /* The input is put in age */
        if ( age < 100 ) {                  /* If the age is less than 100 */
            printf ("You are pretty young!\n" ); /* Just to show you it works... */
        }
        else if ( age == 100 ) {            /* I use else just to show an example */ 
            printf( "You are old\n" );       
        }
        else {
            printf( "You are really old\n" );     /* Executed if no other statement is */
        }
        return 0;
}

This is a pretty classic problem. 这是一个非常经典的问题。 Your output stream has not been flushed. 您的输出流尚未刷新。 Usually this happens after writing a newline (which you are not doing). 通常,这是在编写换行符之后执行的(您没有这样做)。 If you don't want a newline, you could issue a hard flush on standard out: 如果您不希望使用换行符,则可以对标准输出执行硬刷新:

printf( "Please enter your age" );
fflush( stdout ); 
scanf( "%d", &age );

While I'm here, can I ask that you think about your commenting style? 我在这里的时候,能否请您考虑一下您的评论风格? Commenting every line of code is excessive. 注释每一行代码都是多余的。 Anybody who can read code understands what each line does, without needing a comment. 任何可以阅读代码的人都可以理解每一行的内容,而无需评论。 Put comments on their own line, and only to give an overview of several lines of code. 将注释放在自己的行上,仅概述几行代码。 I prefer to see a quick overview of what I'm about to read so I know whether to bother reading it or not. 我更喜欢快速阅读一下我将要阅读的内容,因此我知道是否要阅读它。

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

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