-6

Why 5 is being printed after 1.00.

#include<iostream>
using namespace std;
int main() {
    double x = 1;
    cout << printf("%.2f\n", x);
    return 0;
}

output :

1.00

5

ImBatman
  • 47
  • 8

1 Answers1

1

From the C Standard (7.21.6.3 The printf function)

3 The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

This call of printf

printf("%.2f\n", x)

outputs on console the following characters (shown as a string)

"1.00\n"

That is 5 characters including the new line character '\n'. The return value of the call is 5 according to the quote of the C Standard. And this value is outputted using the operator << for the standard output C++ stream std::cout.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335