C++ 底下 string 與 int 的互轉
string 要轉 int 相對簡單,用 atoi 即可:
#include <cstdlib>
using namespace std;
atoi(input_string.c_str());
using namespace std;
atoi(input_string.c_str());
但 int 要轉 string 就麻煩一點,雖然 itoa 這個 non-standard function 也不算太不常見,但不在標準裡面,最起碼 gcc 就沒支援。標準的作法應該是用 stringstream:
#include <iostream>
#include <stringstream>
using namespace std;
#include <stringstream>
using namespace std;
stringstream ss;
ss << input_number;
cout << ss.str() << endl;
三個問題:首先、atoi 本身名稱有點醜。第二、有 atoi 卻沒有 itoa 是很莫名的不對稱性。第三、用到 stringstream 增加不必要的複雜度。有時候不得不承認 C++ 語法是太過駁雜不純了一點。string int 互轉又很常用…
p.s “>”, “<” 在 code snippet 當中會爛掉,爬了一下 google 暫時沒找到 solution,有空再回來修。若有其他 code display plugin on wordpress 也網友們推薦,找很久了。= =
. 10 Sep 08 | C++ | Comments (5)


