Summary of methods to convert numbers to string in C++

In C++, there are many ways to convert numbers into strings. Here are some commonly used methods:

1 std::to_string() function:

Integers, floating point numbers, and other numeric types can be converted to strings using the std::to_string() function from the C++ standard library, as shown in the previous example.

int num = 42;
double pi = 3.14159;
std::string numStr = std::to_string(num);
std::string piStr = std::to_string(pi);
``

# 2 使用字符串流(std::ostringstream):
可以使用 std::ostringstream 类来将数字转换为字符串,这样可以更精细地控制格式。

```cpp
#include <iostream>
#include <sstream>
#include <string>
 
int main() {
    
    
    int num = 42;
    double pi = 3.14159;
 
    std::ostringstream numStream;
    numStream << num;
    std::string numStr = numStream.str();
 
    std::ostringstream piStream;
    piStream << pi;
    std::string piStr = piStream.str();
 
    std::cout << "Integer as string: " << numStr << std::endl;
    std::cout << "Double as string: " << piStr << std::endl;
 
    return 0;
}

3 Using C library function (sprintf):

Numbers can be formatted into strings using the C library function sprintf.

#include <cstdio>
#include <string>
 
int main() {
    
    
    int num = 42;
    double pi = 3.14159;
 
    char numBuffer[20];
    char piBuffer[20];
 
    std::sprintf(numBuffer, "%d", num);
    std::sprintf(piBuffer, "%.2f", pi);
 
    std::string numStr(numBuffer);
    std::string piStr(piBuffer);
 
    return 0;
}

Of these methods, std::to_string() is the most commonly used and recommended method because it is simple, safe, and does not involve manual buffer allocation. However, depending on the specific needs, it is important to choose the appropriate method. If more advanced formatting or other operations are required, other methods may be required.

Summary of methods to convert numbers to string in C++

Guess you like

Origin blog.csdn.net/m0_51233386/article/details/134428312