6 ms·
You can use C-library functions in C++, so just use fprintf, and you can flush however you see fit. I've been writing C++ since basically forever, and find the
by oppositelock 11y ago
You can use C-library functions in C++, so just use fprintf, and you can flush however you see fit. I've been writing C++ since basically forever, and find the streaming operators in C++ to be way too much of a pain. It's doubly painful if you ever consider internationalizing your software.
fprintf(fd, "Number: %.3f\n", number)
Is a whole lot easier than
std::streamsize ss = std::cout.precision();
std::cout << "Number: " << std::setprecision(3) << number << std::setprecision(ss) << std::endl;
Since setting precision is modal, you have to set it back if you don't want to screw up future output.
Streams suck!
- GFK_of_xmaspast 11y agoOne thing that streams have that the c routines don't is type safety and overloading for user-defined output. Also take a look at cppformat for some of the best of both worlds.
- vbezhenar 11y agoModern compilers are smart enough to catch type safety bugs for most printf use-cases.
- oppositelock 11y agoYup, cppformat is nice. I could also have a nice type-safe wrapper around libc functions. It doesn't change the fact that the API in the language is tedious. When you're doing internationalization, a common thing you might do is something along these lines: fprintf(fd, translate_string(context, "Result %d of %d"), num1, num2); The translation may be "%d of %d results" in another language. It's really difficult to map that into streams. Yes, I'm over-simplifying, since you can't have arbitrary placeholders due to order differences between languages, but it's _much_ harder to write simple code with streams than libc, and I stand by that! As for user-defined data, I've added .toString() functions on objects which I can call whenever needed, either from the ostream operator or pass the result to libc.