Search code examples
c++coutscientific-notationiomanip

Can I set a variable that will change the floatfield when using cout?


I want to be able to easily change the floatfield from scientific to fixed dependent on a condition, so my result would change from something like 3.000000e+00 to 3.0, using code that might look something like this:

some_datatype floatfield;
float number = 5.894
if (condition) {
    floatfield = 'scientific';
} else floatfield = 'fixed';
cout << "hello" << floatfield << number << endl;

I'm aware I can achieve the same effect using

float number = 5.894
if (condition) {
    cout << "hello" << scientific << number << endl;
} else cout << "hello" << fixed << number << endl;

But this does not generalise well if I start using more stream format flags.

If some_datatype exists, what is it? If not, is there any other way of changing the stream format flags using a condition?


Solution

  • I/O manipulators are actually functions (!), and the ones you want to switch between happen to have the same signature.

    So, you can use a function pointer to achieve your goal:

    #include <iomanip>
    #include <iostream>
    
    int main()
    {
        using ManipFuncType = std::ios_base&(std::ios_base&);
        const bool condition = true; // or false!
    
        ManipFuncType* floatfield;
        float number = 5.894;
        if (condition)
            floatfield = std::scientific;
        else
            floatfield = std::fixed;
    
        std::cout << "hello" << floatfield << number << std::endl;
    }
    

    (live demo)