Victor
Victor

Reputation: 37

C++ printf only appear in the end

This is the program that I was trying to make to learn

the program works but the message "type the rectangle height" and "type the rectangle width" only appear when the program is over

#include < stdio.h >

using namespace std;

float calculateArea(float a, float b)
{
    return a * b;
}

float calculatePerimeter(float a, float b)
{
    return 2*a + 2*b;
}

void showMessage(char *msg, float vlr)
{
    printf("%s %5.2f", msg, vlr);
}

int main()
{
    float height, width, area, perimeter;

    printf("type the rectangle height");

    scanf("%f%*c", &height);

    printf("type the rectangle width");

    scanf("%f%*c", &width);

    area = calculateArea(height, width);

    perimeter = calculatePerimeter(height, width);

    showMessage("The area value is =", area);

    showMessage("The perimeter value is =", perimeter);

    return 0;
}

Upvotes: 3

Views: 1490

Answers (2)

built1n
built1n

Reputation: 1546

Of course you can print a newline:

printf("\n");

or using C++ iostreams

cout << endl;

If you wish, you can force the program to flush its output stream:

fflush(stdout);

or using C++ iostreams

cout << flush;

This saves you from having to type a newline if you don't wish to do so.

Upvotes: 4

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137547

You need to print a newline:

void showMessage(char *msg, float vlr)
{
    printf("%s %5.2f\n", msg, vlr);
    //          ----^
}

The reason is because, by default, stdout is line-buffered - that means the content you write to the stream is buffered until a newline character is written. At that point, the buffer will be flushed and actually written to the console.

Upvotes: 1

Related Questions