今天跟一个在腾讯工作的同学聊天了,他问我如何将一个数转换为一个字符串,我跟他说是这样的:
char buffer[10];
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
_itoa(i, buffer, 10);
可是他说不一定是int型转化为字符串,我着这样回答的:循环将这个数字乘以10,计数。转化为long型后,使用_ltoa()函数,然后再在相应的位置上加上一个小数点。现在想想这是一个很笨的解决方案。他说其实只需要一行代码就可以了,我看后感觉很好,也很常用,写到这里供大家参考。
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
#define toString(x) #x
这个宏就可以将所有的数字,包括int型、long型和double型转换为相对应的字符串。关于这种类似的用法还有:
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
#define makechar(x) #@x
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
a = makechar(b);
这个结果就相当于a='b'。
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
#define stringer( x ) printf( #x
"\n" )
void main()
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
{
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
stringer( In quotes
in the printf function call\n );
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
stringer(
"In quotes when printed to the screen"\n );
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
stringer(
"This: \" prints an escaped double quote" );
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
}
//预处理时将会产生如下代码。
void main()
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
{
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
printf(
"In quotes in the printf function call\n" "\n" );
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
printf(
"\"In quotes when printed to the screen\"\n" "\n" );
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
printf(
"\"This: \\\" prints an escaped double quote\"" "\n" );
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
}
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
运行结果:
![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
In quotes
in the printf function call
"In quotes when printed to the screen"
"This: \" prints an escaped double quotation mark"![](http://panpan.blog.51cto.com/images/editer/InBlock.gif)
这种用法可以省去转义字符(\),很方便代码的编写。
关于#的用法还有很多,希望有兴趣的读者能够留言,我们一起讨论。
本文出自 “C++技术” 博客,请务必保留此出处http://panpan.blog.51cto.com/489034/102813
实践:
#define toString(x) (#x)
#define stringer(x) (printf(#x"\n"))
#define mynameandbirthday(x) ("hekexin"#x)
int main()
{
std::string str(toString(1000));
std::cout<<str<<std::endl;
stringer(hello world);
stringer(1234fff5455);
std::cout<<mynameandbirthday(19841102)<<std::endl;
std::cout<<mynameandbirthday(19841223)<<std::endl;
return 0;
}