C++ 字符串和数字相互转化的方法总结归纳

C++ 字符串和数字相互转化的方法总结归纳

一、sscanf和sprintf

sscanf(源字符串,格式,目的变量) 字符串数组转化为数字 理解为string + scanf
sprintf(目的字符串,格式,源变量) 数字转化为字符串数组 理解为string + printf
例如:

#include <cstdio>
int main(){
    int n;
    char str[10] = "123";
    sscanf(str,"%d",&n);    //将字符串数组的内容转化为数字
    printf("%d",n);
}

输出为

123
#include <cstdio>
int main(){
    int n = 1234;
    char str[10];
    sprintf(str,"%d",n);    //将数字内容相应写入字符串
    printf("%s",str);
}

输出为

1234

二、atoi、stoi字符串转数字

atoi、stoi均为cstring头文件下的字符处理函数,作用为把字符串转化为数字
atoi(const *char)若参数为string类型,一定先要用c_str()方法进行处理(返回一个指向标准c字符串数组的指针)
stoi(const *string) 函数名为string to integer缩写
其中atoi()不进行范围检查;而stoi()进行范围检查,默认为int,若超出范围则报错

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s1 = "2147482", s2 = "-214748";
    string s3 = "214748666666663", s4 = "-21474836488";
    cout << stoi(s1) << endl;
    cout << stoi(s2) << endl;
    cout << atoi(s3.c_str()) << endl;
    cout << atoi(s4.c_str()) << endl;
    return 0;
}
2147482
-214748
301866663
-8

三、数字转字符串

● itoa():将整型值转换为字符串。
● ltoa():将长整型值转换为字符串。
● ultoa():将无符号长整型值转换为字符串。
● gcvt():将浮点型数转换为字符串,取四舍五入。
● ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。
● fcvt():指定位数为转换精度,其余同ecvt()。

# include <stdio.h>
# include <stdlib.h>
int main ()
{
    int num_int = 435;
    double num_double = 435.10f;
    char str_int[30];
    char str_double[30];  
    itoa(num_int, str_int, 10);  //把整数num_int转成字符串str_int,10表示10进制
    gcvt(num_double, 8, str_double);  //8代表精度
    printf("str_int: %s\n", str_int);
    printf("str_double: %s\n", str_double);
    return 0;
 }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值