C++FAQ

Sunday, January 29, 2006

 

如何把數值形別變成字串形別?

Q: 如何把數值形別變成字串形別?

A:

舊時 C 的做法 (已不被建議使用):
char c[10]; // simply large enough - don't forget the
// extra byte needed for the trailing '\0'
int i = 1234;
sprintf(c, "%d", i);
可以在如MSDN查到'sprintf()'的細節。

使用 'CString':
int i = 1234;
CString cs;
cs.Format("%d", i);
使用的方式類似於'sprintf()'。可以在MSDN查到更多細節。

注意: 如果指定的specifiers (也就是上面'%d'的部份)與實際傳入的參數不同,將會造成不可預期的結果,'sprintf()'與'CString::Format()'都要小心這種錯誤。


C++的做法

下面的這個例子告訴你如何使用標準的C++ class來做:

#include <string>
#include <sstream>
#include <iostream>

template <class T>
std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))

{
std::ostringstream oss;
oss << f << t;

return oss.str();
}

int main()

{
// the second parameter of to_string() should be one of
// std::hex, std::dec or std::oct
std::cout<<to_string<long>(123456, std::hex)<<std::endl;

std::cout<<to_string<long>(123456, std::oct)<<std::endl;

return 0;
}

/* output:
1e240
361100
*/



這個方法不只非常漂亮,而且是type safe的,因為Compiler在compile time時根據運算元(operand)的形別選擇適當的'std::ostringstream::operator << ()'。

另外: (下面這段不知道怎麼翻)

There is a new method with 'boost::format', which combines the advantages of printf with the type-safety and extensibility of streams.

One of the advantages (as with printf) is you can store the entire format string as a template (not a C++ template). This is better for internationalisation (making string tables), as well as the fact that even just using a local string table can significantly reduce the code-size.

Comments: Post a Comment



<< Home

Archives

January 2006   February 2006  

This page is powered by Blogger. Isn't yours?