C++字符串和数字转换

本文介绍了在C++中将字符串转换为数字的两种方法,包括使用ASCII码和标准库中的转换函数如atoi、atol、atoll和atof。同时,也展示了如何将数字转换为字符串,利用printf和sprintf函数将不同类型的数字(int、longlong、double)格式化输出到屏幕或char数组中。
摘要由CSDN通过智能技术生成

字符串转数字:

方法一: 用ASCII码

char s[1] = {'9'};
int a = s[0] - '0';
cout << "a: " << a << endl;

不过只能进行单个字符转换

方法二:

头文件: <cstdlib> 

函数:
int atoi(const char *str):        //字符串转int 
long atol(const cahr *str):        //字符串转long
long long atoll(const cahr *str):        //字符串转long long
double atof(const char *str):         //字符串转double

转换成哪一个,就调用哪个函数

std::cout << std::atoi("123") + 3 << std::endl;		//字符串转数字+3并输出
std::cout << std::atof("123.5") + 3.2 << std::endl; //调用longlong的函数
std::cout << std::atoi("123a5") << std::endl;	    //遇到字母,只转换前面的数字 

或者直接赋值即可

int num = atoi("123");
cout << num;

    数字 -> 字符串
    //sprintf(char数组, "%d", 变量名); 


  

//定义三个不同类型的数字变量
int a = 10;
long long b = 456;
double c = 13.2;
cout << "数字转字符串" << endl; 
    
//直接打印到屏幕上 
std::printf("%d\n", a);
std::printf("%lld", b);
std::printf("%f\n", c); 

//放到char数组里
char arr[400] = {};

std::sprintf(arr, "%d", d);
std::cout << arr << std::endl;     //输出

std::sprintf(arr, "%lld", k);
std::cout << arr << std::endl;

std::sprintf(arr, "%f", e); 
std::cout << arr << std::endl;    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值