c++中字符串与数字的转换
来源:互联网 发布:幻 游戏 知乎 编辑:程序博客网 时间:2024/06/07 02:15
字符串流类(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;}输出结果:
阅读全文
0 0
- C语言中字符串与数字间的转换
- C/C++中字符串与数字之间的转换
- c语言中数字与字符串的转换
- C/C++中数字与字符串之间的转换
- C语言中字符串与数字间的转换
- C 字符串与数字的转换
- C++中数字与字符串的转换
- c++中字符串与数字的转换
- Java中数字字符串与对应数字的转换
- C/C++中字符串与数字间转换方法
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- C/C++中字符串与数字相互转换
- 针对mybatis的理解
- XTU1167 逆序数
- Linux 中如何卸载已安装的软件
- 测试报告参考规范之测试需求
- 小白每天学习两个函数D7-( sprintf,fprintf)
- c++中字符串与数字的转换
- windows操作系统基础知识 API+DLL
- 【莫比乌斯反演】BZOJ2818 Gcd
- 5.K-means 聚类算法
- Python之if判断语句
- mybatis逆向工程 去除表字段前缀 匹配所有表名
- 求积分 [matlab]
- java高效 的判断数组中是否包含特定值
- node搭建服务器详解及模块化