今天跟一个在腾讯工作的同学聊天了,他问我如何将一个数转换为一个字符串,我跟他说是这样的:
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" );
}
//预处理时将会产生如下代码。
void main()
{
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"
这种用法可以省去转义字符(\),很方便代码的编写。
关于#的用法还有很多,希望有兴趣的读者能够留言,我们一起讨论。
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
void main()
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
//预处理时将会产生如下代码。
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
void main()
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
运行结果:
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
In quotes in the printf function call
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
"In quotes when printed to the screen"
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
"This: \" prints an escaped double quotation mark"
![InBlock.gif](p_w_picpaths/editer/InBlock.gif)
关于#的用法还有很多,希望有兴趣的读者能够留言,我们一起讨论。
转载于:https://blog.51cto.com/panpan/102813