Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

writing in c with printf and scanf not working as expected

So I'm a total newb to C. I'm using eclipse with MinGW compiler. I'm on the second chapter using the scanf and printf functions and my program is working, but only printing the statements to the console once I've entered the three ints into the scanf functions.

#include <stdio.h>
int main(void){
    int length, height, width, volume, dweight;

    printf("Enter the box length: ");
    scanf("%d", &length);
    printf("
Enter the box width: ");
    scanf("%d", &width);
    printf("
Enter the box height");
    scanf("%d", &height);

    volume = length * width * height;
    dweight = (volume + 165) / 166;

    printf("Dimensions: l = %d, w = %d, h = %d
", length, width, height);
    printf("Volume: %d
", volume);
    printf("Dimensional Width: %d
", dweight);

    return 0;
}

console output:

8 (user input + "Enter" + key)
10 (user input + "Enter" key)
12 (user input + "Enter" key)
Enter the box length: 
Enter the box width: 
Enter the box heightDimensions: l = 8, w = 10, h = 12
Volume: 960
Dimensional Width: 6

any insights? I'm expecting it to printf, then scanf for user input like so:

Enter the box length: (waits for user int input; ex. 8 + "Enter")
Enter the box width: ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just add fflush(stdout); after each printf() before you call scanf():

#include <stdio.h>
int main(void){
    int length, height, width, volume, dweight;

    printf("Enter the box length: "); fflush(stdout);
    scanf("%d", &length);
    printf("
Enter the box width: "); fflush(stdout);
    scanf("%d", &width);
    printf("
Enter the box height"); fflush(stdout);
    scanf("%d", &height);

    volume = length * width * height;
    dweight = (volume + 165) / 166;

    printf("Dimensions: l = %d, w = %d, h = %d
", length, width, height);
    printf("Volume: %d
", volume);
    printf("Dimensional Width: %d
", dweight);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...