数值和字符串互相转换

简介:
  今天看书看到了strintstream,感觉用起来很方便,尤其是将数值转换为字符串的时候使用stringstream,可以达到非常美妙的效果。对比前面我的一篇文章--如何将数字转换为字符串,使用#的方法,使用stringstream也是一种很好的选择。
  废话不多说,直接看代码吧。
  main.cpp文件:
InBlock.gif#include <iostream>
InBlock.gif#include <sstream>
InBlock.gif using  namespace std;
InBlock.gif
  int main()
InBlock.gif{
InBlock.gif  stringstream ss;     //流输出
InBlock.gif  ss <<  "there are " << 100 <<  " students.";
InBlock.gif  cout << ss.str() << endl;
InBlock.gif
   int intNumber = 10;     //int型
InBlock.gif  ss.str("");
InBlock.gif  ss << intNumber;
InBlock.gif  cout << ss.str() << endl;
InBlock.gif
   float floatNumber = 3.14159f;   //float型
InBlock.gif  ss.str("");
InBlock.gif  ss << floatNumber;
InBlock.gif  cout << ss.str() << endl;
InBlock.gif
   int hexNumber = 16;         //16进制形式转换为字符串
InBlock.gif  ss.str("");
InBlock.gif  ss << showbase << hex << hexNumber;
InBlock.gif  cout << ss.str() << endl;
InBlock.gif   return 0;
InBlock.gif}
  输出结果如下:
there are 100 students.
10
3.14159
0x10
  可以看出使用stringstream比较使用#的好处是可以格式化数字,以多种形式(比如十六进制)格式化,代码也比较简单、清晰。

  同样,可以使用stringstream将字符串转换为数值:
InBlock.gif#include <iostream>
InBlock.gif#include <sstream>
InBlock.gif using  namespace std;
InBlock.gif
  template< class T>
InBlock.gifT strToNum( const  string& str)   //字符串转换为数值函数
InBlock.gif{
InBlock.gif  stringstream ss(str);
InBlock.gif  T temp;
InBlock.gif  ss >> temp;
InBlock.gif   if ( ss.fail() ) {
InBlock.gif     string excep =  "Unable to format ";
InBlock.gif    excep += str;
InBlock.gif     throw (excep);
InBlock.gif  }
InBlock.gif   return temp;
InBlock.gif}

InBlock.gif int main()
InBlock.gif{
InBlock.gif   try {
InBlock.gif     string toBeFormat =  "7";
InBlock.gif     int num1 = strToNum< int>(toBeFormat);
InBlock.gif    cout << num1 << endl;
InBlock.gif
    toBeFormat =  "3.14159";
InBlock.gif     double num2 = strToNum< double>(toBeFormat);
InBlock.gif    cout << num2 << endl;
InBlock.gif
    toBeFormat =  "abc";
InBlock.gif     int num3 = strToNum< int>(toBeFormat);
InBlock.gif    cout << num3 << endl;
InBlock.gif  }
InBlock.gif   catch ( string& e) {
InBlock.gif    cerr <<  "exception:" << e << endl;
InBlock.gif  }
InBlock.gif   return 0;
InBlock.gif}

  这样就解决了我们在程序中经常遇到的字符串到数值的转换问题。





     本文转自panpan3210 51CTO博客,原文链接:http://blog.51cto.com/panpan/107732,如需转载请自行联系原作者


相关文章
|
2月前
将整数转换为枚举
将整数转换为枚举。
16 2
C#中字符串是否可以转换为数值
C#中字符串是否可以转换为数值
|
JavaScript 前端开发
数值、字符串、数组的相互转换
今天是我第一天刷力扣,我就想着通过刷题来巩固一下之间学习过的知识。 然后有一道题就需要将数字转换为字符串,然后倒转,比较是否相等。 这里我就想把之前学习到数字、字符串、数组的相互转换方法总结一下。
062.浮点数转换为字符串
062.浮点数转换为字符串
95 0
018.任意进制数的转换
018.任意进制数的转换
64 0
|
开发者 Python
转换成为字符串和浮点数|学习笔记
快速学习转换成为字符串和浮点数
80 0
|
开发者 Python
转换成为整数|学习笔记
快速学习转换成为整数
73 0
c++数字和字符串的转换
c++数字和字符串的转换
198 0
|
机器学习/深度学习 存储 JavaScript
数据类型-数值和字符串 | 学习笔记
快速学习数据类型-数值和字符串。