数值和字符串互相转换

  今天看书看到了strintstream,感受用起来很方便,尤为是将数值转换为字符串的时候使用stringstream,能够达到很是美妙的效果。对比前面个人一篇文章--如何将数字转换为字符串,使用#的方法,使用stringstream也是一种很好的选择。
  废话很少说,直接看代码吧。
  main.cpp文件:
#include <iostream>
#include <sstream>
using namespace std;

  int main()
{
  stringstream ss;     //流输出
  ss << "there are " << 100 << " students.";
  cout << ss.str() << endl;

   int intNumber = 10;     //int型
  ss.str("");
  ss << intNumber;
  cout << ss.str() << endl;

   float floatNumber = 3.14159f;   //float型
  ss.str("");
  ss << floatNumber;
  cout << ss.str() << endl;

   int hexNumber = 16;         //16进制形式转换为字符串
  ss.str("");
  ss << showbase << hex << hexNumber;
  cout << ss.str() << endl;
   return 0;
}
  输出结果以下:
there are 100 students.
10
3.14159
0x10
  能够看出使用stringstream比较使用#的好处是能够格式化数字,以多种形式(好比十六进制)格式化,代码也比较简单、清晰。

  一样,能够使用stringstream将字符串转换为数值:
#include <iostream>
#include <sstream>
using namespace std;

  template< class T>
T strToNum( const string& str)   //字符串转换为数值函数
{
  stringstream ss(str);
  T temp;
  ss >> temp;
   if ( ss.fail() ) {
     string excep = "Unable to format ";
    excep += str;
     throw (excep);
  }
   return temp;
}

int main()
{
   try {
     string toBeFormat = "7";
     int num1 = strToNum< int>(toBeFormat);
    cout << num1 << endl;

    toBeFormat = "3.14159";
     double num2 = strToNum< double>(toBeFormat);
    cout << num2 << endl;

    toBeFormat = "abc";
     int num3 = strToNum< int>(toBeFormat);
    cout << num3 << endl;
  }
   catch ( string& e) {
    cerr << "exception:" << e << endl;
  }
   return 0;
}
  这样就解决了咱们在程序中常常遇到的字符串到数值的转换问题。
相关文章
相关标签/搜索