int main() {
    int input = 0;
    do {
        if(input > 1) {
            printf("You entered");
            break;
        }

        printf("Enter an integer (> 1): ");
        scanf("%d",&input);

    } while(input < 2);

    return 0;
}

Hello, I'm new to C. Could anyone explain what break does? In this program, the statement before break "You entered" doesn't show up on the console. I know java but this works totally different.

有帮助吗?

解决方案

There is no integer exist between 1 and 2. Change

if(input > 1)  

to

if(input > 0)  

After that if you enter 1 then program enters the if body then print You entered and on encountering the break statement, immediately terminates the do-while loop.

其他提示

The "break" statement causes your code to exit the loop immediately.

You're not seeing any output because you only loop while the input is strictly less than 2, but your if statement is looking for input that's strictly greater than 1.

That's not going to work; if you enter 1, the if statement won't execute (because 1 > 1 is false), and if you enter 2, the loop exits immediately (because 2 < 2 is false).

You either need to loop while input <= 2, or you need to test for input >= 1.

Having said all that...

Standard output is usually line-buffered, meaning you won't see anything show up on your console until the buffer is full or you send a newline character. You either need to manually flush the stream or send a newline as part of the format string; either

printf("You entered");
fflush(stdout);        

or

printf("You entered\n");

should work.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top