在程序中需要將一個(gè)正整數(shù)(如123)轉(zhuǎn)換成一個(gè)固定長(zhǎng)的串(如8位,00000123)。算法有很多了。我采用可以這個(gè)方法123+10^8=100000123,將100000123轉(zhuǎn)換成串"100000123",然后返回這個(gè)串的子串substr(1)。在這個(gè)方法當(dāng)中會(huì)涉及指數(shù)的運(yùn)算,C++只能作浮點(diǎn)數(shù)的指數(shù)運(yùn)算,為提高效率使用模板元編程,將這一過程提前到編譯期完成。程序很簡(jiǎn)單,大家看看就明白了:
????template<int?d,int?pow>
????struct?Power
????{
????????static?const?int?value?=?Power<d,pow-1>::value?*?d;
????};
????template<int?d>
????struct?Power<d,0>
????{
????????static?const?int?value?=?1;
????};
????/**
?????*?該函數(shù)將一個(gè)整數(shù)轉(zhuǎn)換成固定長(zhǎng)度的0不齊的串,如12->"00012"
?????*/
????template<int?len>
????std::string?int_cast_zerostr(const?int?i)
????{
????????std::string?result??=?boost::lexical_cast<std::string>(Power<10,len>::value?+?i);
????????return?result.substr(1);
????}
如果要將12轉(zhuǎn)換成"00000012",可使用函數(shù)int_cast_zerostr<8>(12)。
謝謝小明的提醒,想起B(yǎng)oost有個(gè)format庫,所以可以這樣
????boost::format?f("%08d");
????std::string?s?=?(f%12).str();
????std::cout<<s; //s = "00000012"
不過個(gè)人更喜歡int_cast_zerostr<8>(12)方式。呵呵!