c++中字符串与数字的转换

字符串流类(sstream)用于string的转换

<sstream>:相关头文件

istringstream:字符输入流

ostringstream:字符输出流

使用方法:

#include <sstream>
#include <string>
#include <iostream>
using namespace std;
bool StrToNum(const string& s , int& n)//return bool 
{
    istringstream iss(s);
    return iss >> n;
}
bool StrToNum(const string& s , double& n)
{
    istringstream iss(s);
    return iss >> n;
}
bool StrToNum(const string& s , float& n)  
{
    istringstream iss(s);
    return iss >> n;
}
string NumToStr(int& n)
{
    ostringstream oss;
    oss << n;
    return oss.str();
}
string NumToStr(double& n)
{
    ostringstream oss;
    oss << n;
    return oss.str();
}
string NumToStr(float& n)
{
    ostringstream oss;
    oss << n;
    return oss.str();
}

int main()
{	
    int i = 0;
    cout << StrToNum("123",i) <<endl;
    cout << i <<endl;
	
    double d = 0;
    cout << StrToNum("123.123",d) <<endl;
    cout << d <<endl;
	
    float f = 0;
    cout << StrToNum("456.234",f) <<endl;
    cout << f <<endl;
	
    int ni = 123;
    cout <<NumToStr(ni)<<endl;
	
    float nf = 123.456;
    cout <<NumToStr(nf)<<endl;
	
    double nd = 678.908;
    cout <<NumToStr(nd)<<endl;
	
    return 0;
}

输出结果:


那现在就出现了一个问题?利用函数重载的方式这么多数据类型我们都需要一个函数一个函数的写吗?能不能只用一个函数就实现这个功能呢?

尝试一下利用C语言宏定义的方式定义函数

#include <sstream>
#include <string>
#include <iostream>
using namespace std;
#define TO_NUMBER(s,n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream () <<n)).str() )
int main()
{	
	int i;
	if( TO_NUMBER("123",i) )
	{
		cout << i<< endl;
	}
	float f;
	if( TO_NUMBER("123.123",f) )
	{
		cout << f<< endl;
	}
	double d;
	if( TO_NUMBER("1.12345",d) )
	{
		cout << d << endl;
	}
	string s = "";
	
	
	cout <<TO_STRING(123) << endl;
	
	cout <<TO_STRING(123.123) << endl;
	
	cout <<TO_STRING(1.12345) << endl;
	
	return 0;
}
输出结果:




  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值