Thursday, October 7, 2010

[C++] convert int to string with the employment of STL / sstream


Abstract
在C語言中, 當「int」型別要轉換成「char *」型別時, 可以透過「sprintf()」來實作。而在C++中, 當「int」型別要轉換成「string」型別時,我們則可以透過stringstream來實作。本文目的是紀錄如何透過stringstream」來將int型別為「string型別



Example
/*
Author      : Trek
Description : Convert int to string with the employment of STL/sstream
Compiler    : g++

http://seeyababy.blogspot.com
*/

/* To use the stringstream, we must include the sstream header */
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main ()
{
    /* initialization */
    int a = 7207;
    string s;

    /* creates a stringstream that holds a copy of the string s */
    stringstream ss(s);

    /* auto formatting across an arithmetic type and a string type */
    ss << a;

    /* use the str member to obtain a copy of the string associated with the stringstream we just created. */
    s = ss.str();

    cout << s << endl;

    return 0;
}


Postscript
會有這麼一篇筆記的原因是, 筆者在coding時常常需要同時output許多圖片到某個資料夾, 此時如果將數字轉成字串, 那麼就可以"方便地append"在一些路徑下了 :)
 

Reference
  • C++ Primer, 4th Edition, S. B. Lippman, J. Lajoie and B. E. Moo

0 意見: