數值和字符串互相轉換

  今天看書看到了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;
}
  這樣就解決了咱們在程序中常常遇到的字符串到數值的轉換問題。
相關文章
相關標籤/搜索