ISsue with modifying std::cout

I have,
1
2
3
4
double temp_price;
std::cout << "Price?\n> "; //12345.6789
std::cin >> temp_price;
std::cout << "Price\t\t >> " << std::cout.setf(std::ios::fixed) << std::cout.precision(4) << temp_price << " <<" << std::endl;


1
2
3
4
5
Expected Output:
>>12345.6789<<

Actual output:
>>513612345.6789<<


Any thoughts why this is happening?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>

int main()
{
    double temp_price;
    std::cout << "Price?\n> "; //12345.6789
    std::cin >> temp_price;

    // **** don't do this
    // std::cout << "Price\t\t >> " << std::cout.setf(std::ios::fixed) << std::cout.precision(4) << temp_price << " <<" << std::endl;

    // this is fine
    std::cout << "Price\t\t >> " << std::fixed << std::setprecision(4) << temp_price << " <<" << std::endl;

    // this would also have been fine
    std::cout.setf(std::ios::fixed) ;
    std::cout.precision(4) ;
    std::cout << "Price\t\t >> " << std::fixed << std::setprecision(4) << temp_price << " <<" << std::endl;
}


> Any thoughts why this is happening?

std::cout.setf(std::ios::fixed) returns the old format flags (ones before the call to the function).
std::cout.precision(4) returns the old precision (the precision before the function was called).

These two values get printed (if the format flags are of some output streamable type).
Last edited on
Topic archived. No new replies allowed.