Home >Backend Development >C++ >How Can I Efficiently Embed Formatted std::strings into File Streams in Modern C ?
Embedding Formatted std::string in File Streams with sprintf
Modern C streamlines the integration of sprintf-formatted std::strings into file streams. Newer techniques offer significant improvements over legacy methods.
C 20
C 20 introduces std::format, enabling straightforward string formatting using python-like replacement fields:
#include <iostream> #include <format> int main() { std::cout << std::format("Hello {}!\n", "world"); }
C 11
C 11's std::snprintf provides a safe and user-friendly option:
#include <memory> #include <string> #include <stdexcept> template<typename ... Args> std::string string_format(const std::string& format, Args ... args) { int size_s = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1; if (size_s <= 0) { throw std::runtime_error("Error during formatting."); } size_t size = static_cast<size_t>(size_s); std::unique_ptr<char[]> buf(new char[size]); std::snprintf(buf.get(), size, format.c_str(), args ...); return std::string(buf.get(), buf.get() + size - 1); }
注意事项
Additional Options
Conclusion
Modern C techniques vastly improve upon older approaches for incorporating formatted std::strings into file streams. Opting for C 20's std::format provides the most streamlined and secure solution. C 11's std::snprintf offers a solid alternative for backwards compatibility, while external libraries like {fmt} can further enhance functionality.
The above is the detailed content of How Can I Efficiently Embed Formatted std::strings into File Streams in Modern C ?. For more information, please follow other related articles on the PHP Chinese website!