c++ 数字和string 类型的相互转换

发布时间 2023-04-04 14:21:53作者: 卑以自牧lq

C++ 数字和 string 类型的相互转换

数字转为 string

1.std::to_string() 函数

// Defined in header <string>
std::string to_string(int value);                   // (since C++11)
std::string to_string(long value);                  // (since C++11)
std::string to_string(long long value);             // (since C++11)
std::string to_string(unsigned value);              // (since C++11)
std::string to_string(unsigned long value);         // (since C++11)
std::string to_string(unsigned long long value);    // (since C++11)
std::string to_string(float value);                 // (since C++11)
std::string to_string(double value);                // (since C++11)
std::string to_string(long double value);           // (since C++11)

example:

#include <iostream>
#include <string>
 
int main()
{
    int i = 23;
    std::string str = std::to_string(i); // 把 i 转为 string 并赋值给 str
    std::cout << str << std::endl; // str = "23"
}

2.stringstream 类

example:

#include <iostream>
#include <string>
#include <sstream>
 
int main()
{
    int a = 10;
    std::stringstream ss;
    ss << a;
    std::string str = ss.str(); // str = "10"
    std::cout << str << std::endl;
}

3.springf

把数字转为 char*, 再转为string。

int sprintf( char* buffer, const char* format, ... );

example:

#include <iostream>
#include <string>
#include <cstdio>
 
int main()
{
    int i = 23;
    char* buf = (char*)malloc(20); // 分配内存
    std::sprintf(buf, "%d", i);
    std::string str = std::string(buf);
    std::cout << str << std::endl; // str = "23"
}

string 转为数字

unsigned long       stoul(const std::string& str, std::size_t* pos = nullptr, int base = 10);
unsigned long long  stoull( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

int                 stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
long                stol( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
long long           stoll( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

float               stof( const std::string& str, std::size_t* pos = nullptr );
double              stod( const std::string& str, std::size_t* pos = nullptr );
long double         stold( const std::string& str, std::size_t* pos = nullptr );

example:

#include <iostream>
#include <string>
#include <cstdio>
using namespace std;

int main()
{
    string str = "-123.556";

    unsigned long u = stoul(str); // u = 4294967173; 应该是先转为 32 位带符号的整型,再转为 unsigned long   

    unsigned long long lu = stoull(str); // lu = 18446744073709551493; 转为 64 位带符号的整型,再转为无符号的

    int i = stoi(str); // i = -123

    float f = stof(str); // f = -123.556
}