天天看點

數值和字元串互相轉換

  今天看書看到了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;

  float floatNumber = 3.14159f;  //float型

  ss << floatNumber;

  int hexNumber = 16;        //16進制形式轉換為字元串

  ss << showbase << hex << hexNumber;

  return 0;

}

  輸出結果如下:

there are 100 students.

10

3.14159

0x10

  可以看出使用stringstream比較使用#的好處是可以格式化數字,以多種形式(比如十六進制)格式化,代碼也比較簡單、清晰。

  同樣,可以使用stringstream将字元串轉換為數值:

  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;

  這樣就解決了我們在程式中經常遇到的字元串到數值的轉換問題。

     本文轉自panpan3210 51CTO部落格,原文連結:http://blog.51cto.com/panpan/107732,如需轉載請自行聯系原作者