C++中数字和字符串之间的转换

VS2017

#include <iostream>
using std::cout;
using std::endl;
using std::string;
#include <sstream>//stringstream


int main()
{
	//方式一:c语言库函数
	{
		//字符串转换为数字 atoi() atof()
		string stra = "527";
		string strb = "123.123654";
		int numa = atoi(stra.c_str());
		double numb = atof(strb.c_str());
		cout << "numa = " << numa << endl;//527
		cout << "numb = " << numb << endl;//123.124
		//数字转换为字符串 itoa() gcvt() 这两个函数被编译器警告
		int intV = 212;
		double douV = 2018.052721;
		char s1[15] = "";
		char s2[15] = "";
		itoa(intV, s1, 10);
		gcvt(douV, 6, s2);
		cout << "s1 = " << s1 << endl;//212
		cout << "s2 = " << s2 << endl;//2018.05
		
		char s[20] = "";
		sprintf(s, "%.3f", douV);//sprintf() 格式化字符串, 被编译器警告
		cout << "s = " << s << endl;//2018.053
	}
	//方式二:stringstream
	{
		//字符串转化为数字
		string s1 = "12", s2 = "3.141592";
		int n1 = 0;
		double n2 = 0;
		std::stringstream ss1, ss2;
		ss1 << s1;
		ss1 >> n1;
		ss2 << s2;
		ss2 >> n2;
		cout << "n1 = " << n1 << endl;//12
		cout << "n2 = " << n2 << endl;//3.14159
		//数字转换为字符串
		int num1 = 123;
		double num2 = 54.123456;
		string str1 = "", str2 = "";
		std::stringstream tmp1,tmp2;
		tmp1 << num1;
		tmp1 >> str1;
		tmp2 << num2;
		tmp2 >> str2;
		cout << "str1 = " << str1 << endl;//123
		cout << "str2 = " << str2 << endl;//54.1235
	}
	//方式三:to_string --- stoi stof
	{
		//数字转换为字符串
		int a = 15;
		double b = 2.7182818;
		cout << "strA = " << std::to_string(a) << endl;//15
		cout << "strB = " << std::to_string(b) << endl;//2.718282
        //字符串转换为数字
        string aa = "1234";
	    string bb = "512.2625";
	    int num1 = stoi(aa);
	    float num2 = stof(bb);
	    cout << num1 << " " << num2 << endl;//1234 512.263
	}
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值