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++



Try boost::lexical_cast:
void foo(const string& input)
{
int output = lexical_cast<int>(input);
}
BTW, 你是用 WYSIWYG editor 寫 blog 的對吧?
就我知道, 辛苦點改用 html editor 才能避開 < > 的問題.
f大,我試過用 html editor,此問題暫時無解。
因為只要碰到 code block 就會丟給 plugin 去處理,所以是 plugin 的問題…
BTW,lexical_cast 漂亮多了,感謝分享!
jutirain,
客氣了. 除了年紀漸漸大了, 其他的我不敢稱大.
我自已比較愛用strtol,因為可以通吃 hex oct 和dec,試了一下 lexical_cast 對 hex 和oct 一樣沒救,有比較好的方法嗎