字符串流类(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;
}
输出结果: