今天跟一个在腾讯工作的同学聊天了,他问我如何将一个数转换为一个字符串,我跟他说是这样的:
InBlock.gif char buffer[10];
InBlock.gif_itoa(i, buffer, 10);
可是他说不一定是int型转化为字符串,我着这样回答的:循环将这个数字乘以10,计数。转化为long型后,使用_ltoa()函数,然后再在相应的位置上加上一个小数点。现在想想这是一个很笨的解决方案。他说其实只需要一行代码就可以了,我看后感觉很好,也很常用,写到这里供大家参考。
InBlock.gif#define toString(x) #x
这个宏就可以将所有的数字,包括int型、long型和double型转换为相对应的字符串。关于这种类似的用法还有:
InBlock.gif#define makechar(x)    #@x
InBlock.gifa = makechar(b);
这个结果就相当于a='b'。
InBlock.gif#define stringer( x ) printf( #x "\n" )
InBlock.gif
  void main()
InBlock.gif{
InBlock.gif        stringer( In quotes in the printf function call\n );
InBlock.gif        stringer( "In quotes when printed to the screen"\n );    
InBlock.gif        stringer( "This: \"    prints an escaped double quote" );
InBlock.gif}
InBlock.gif
  //预处理时将会产生如下代码。
InBlock.gif
  void main()
InBlock.gif{
InBlock.gif     printf( "In quotes in the printf function call\n" "\n" );
InBlock.gif     printf( "\"In quotes when printed to the screen\"\n" "\n" );
InBlock.gif     printf( "\"This: \\\" prints an escaped double quote\"" "\n" );
InBlock.gif}
InBlock.gif
  运行结果:
InBlock.gif
  In quotes in the printf function call
InBlock.gif
  "In quotes when printed to the screen"
InBlock.gif
  "This: \" prints an escaped double quotation mark"
InBlock.gif
这种用法可以省去转义字符(\),很方便代码的编写。
关于#的用法还有很多,希望有兴趣的读者能够留言,我们一起讨论。