std::string.resize() and std::string.length()

后端 未结 7 951
闹比i
闹比i 2020-12-11 23:51

I\'m relatively new to C++ and I\'m still getting to grips with the C++ Standard Library. To help transition from C, I want to format a std::string using printf

相关标签:
7条回答
  • 2020-12-12 00:22

    To help transition from C, I want to format a std::string using printf-style formatters.

    Just don't :(

    If you do this, you're not actually learning C++ but coding C with a C++ compiler. It's a bad mindset, bad practice, and it propagates the problems that the std::o*stream classes were created to avoid.

    I realise stringstream is a more type-safe approach, but I find myself finding printf-style much easier to read and deal with (at least, for the time being).

    It's not a more typesafe approach. It is a typesafe approach. More than that, it minimizes dependencies, it lowers the number of issues you have to keep track of (like explicit buffer allocation and keeping track of the null char terminator) and it makes it easier to maintain your code.

    Above that it is completely extensible / customizable:

    • you can extend locale formatting

    • you can define the i/o operations for custom data types

    • you can add new types of output formatting

    • you can add new buffer i/o types (making for example std::clog write to a window)

    • you can plug in different error handling policies.

    std::o*stream family of classes is very powerful and once you learn to use it correctly there's little doubt you will not go back.

    Unless you have very specific requirements your time will probably be much better spent learning the o*stream classes than writing printf in C++.

    0 讨论(0)
提交回复
热议问题