Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple I/O manipulator not working as intended

Tags:

c++

io

the following code:

#include <iostream>

std::ios_base &my_manip (std::basic_ios<char> &os) {
    os.unsetf(std::ios_base::basefield);
    os.setf(std::ios_base::scientific);
    return os;
}

int main (int argc, char **argv) {
    std::cout << 8.8888888 << std::endl;
    std::cout << my_manip << 8.8888888 << std::endl;
    return 0;
}

prints:

8.88889

18.88889

While the following code:

#include <iostream>

std::ios_base &my_manip (std::basic_ios<char> &os) {
    os.unsetf(std::ios_base::basefield);
    os.setf(std::ios_base::scientific);
    return os;
}

int main (int argc, char **argv) {
    std::cout << 8.8888888 << std::endl;
    my_manip(std::cout);
    std::cout << 8.8888888 << std::endl;
    return 0;
}

prints the expected result:

8.88889

8.888889e+00

Can anybody tell me what is wrong with the first version?

like image 591
ben Avatar asked Feb 14 '23 07:02

ben


1 Answers

The custom manipulator signature is not matching,

You should be doing this :

std::ostream& my_manip (std::ostream &os) {
    os.unsetf(std::ios_base::basefield);
    os.setf(std::ios_base::scientific);
    return os;
}

std::cout << my_manip << 8.8888888 << std::endl;
like image 142
P0W Avatar answered Feb 26 '23 03:02

P0W