Get the App
SLTechnology News&Howtos  ›  Development  › 

How to generate formatted standard strings for C++

Shulou Source: shulou.com Published: 2022-06-03 14:06:09 10月02日 Update

This article mainly explains "how C++ generates formatted standard strings". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn how C++ generates formatted standard strings.

Two methods of formatting string

As we all know, C++ 's std::string function is incomplete, and there are no various functions, such as formatting string function.

In python3, two methods of formatting strings are supported, one is C style, the formatting part begins with%, the specific type after%% (for example,% s corresponds to string% d corresponds to integer), the other is type-independent style, {0} corresponds to the first parameter, {1} corresponds to the second parameter.

> "{0}'s age is {1}" .format ("scarlet", 11) "scarlet's age is 11" > "% s's age is% d"% ("scarlet", 11) "scarlet's age is 11"

On the other hand, in C++, we can only use C function to format a buffer with snprintf.

# define BUFFSIZE 512 char buf [BUFFSIZE]; snprintf (buf, BUFFSIZE, "% s's age is% d\ n", "scarlet", 11)

Or use type-independent flow operators

Std::ostringstream os; os

Tags: Format character string clocked buffer buffer function parameter type generation code circumference pi method style Zuchongzhi standard insufficient digit information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MariaDB Redmi Docker Huawei