今天跟一個在騰訊工作的同學聊天了,他問我如何将一個數轉換為一個字元串,我跟他說是這樣的:
char buffer[10];
_itoa(i, buffer, 10);
可是他說不一定是int型轉化為字元串,我着這樣回答的:循環将這個數字乘以10,計數。轉化為long型後,使用_ltoa()函數,然後再在相應的位置上加上一個小數點。現在想想這是一個很笨的解決方案。他說其實隻需要一行代碼就可以了,我看後感覺很好,也很常用,寫到這裡供大家參考。
#define toString(x) #x
這個宏就可以将所有的數字,包括int型、long型和double型轉換為相對應的字元串。關于這種類似的用法還有:
#define makechar(x) #@x
a = makechar(b);
這個結果就相當于a='b'。
#define stringer( x ) printf( #x "\n" )
void main()
{
stringer( In quotes in the printf function call\n );
stringer( "In quotes when printed to the screen"\n );
stringer( "This: \" prints an escaped double quote" );
}
//預處理時将會産生如下代碼。
printf( "In quotes in the printf function call\n" "\n" );
printf( "\"In quotes when printed to the screen\"\n" "\n" );
printf( "\"This: \\\" prints an escaped double quote\"" "\n" );
運作結果:
In quotes in the printf function call
"In quotes when printed to the screen"
"This: \" prints an escaped double quotation mark"
這種用法可以省去轉義字元(\),很友善代碼的編寫。
關于#的用法還有很多,希望有興趣的讀者能夠留言,我們一起讨論。
本文轉自panpan3210 51CTO部落格,原文連結:http://blog.51cto.com/panpan/102813,如需轉載請自行聯系原作者