C++ 字符串与数值的转换

文章介绍了C++中的to_string函数用于数值转String,以及string转int、long、double、float等不同类型的方法,如stoi、stol等,并通过testTypeConvert函数展示了这些转换操作的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++11
 头文件:#include <string>

数值转String

 to_string(val):可以将其他类型转换为string。

String转数值

s:表示整数内容的字符串;
b:(非必须)表示转换所用的基数,默认为10(表示十进制);
p:(非必须)是size_t的指针,用来保存s中第一个非数值字符的下标,p默认为0,即函数不返回下标。

  stoi(s, p, b):string转int

  stol(s, p, b):string转long

  stod(s, p, b):string转double

  stof(s, p, b):string转float

  stold(s, p, b):string转long dluble

  stoul(s, p, b), stoll(s, p, b), stoull(s, p, b)等。

void testTypeConvert()
{
    //int --> string
    int i = 5;
    string s = to_string(i);
    cout << s << endl;
    //double --> string
    double d = 3.14;
    cout << to_string(d) << endl;
    //long --> string
    long l = 123234567;
    cout << to_string(l) << endl;
    //char --> string
    char c = 'a';
    cout << to_string(c) << endl;   //自动转换成int类型的参数
    //char --> string
    string cStr; cStr += c;
    cout << cStr << endl;
 
 
    s = "123.257";
    //string --> int;
    cout << stoi(s) << endl;
    //string --> long
    cout << stol(s) << endl;
    //string --> float
    cout << stof(s) << endl;
    //string --> doubel
    cout << stod(s) << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值