zoukankan      html  css  js  c++  java
  • 如何将数字(包括double型)转换为字符串 (转载)

    今天跟一个在腾讯工作的同学聊天了,他问我如何将一个数转换为一个字符串,我跟他说是这样的:

    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"
    这种用法可以省去转义字符(\),很方便代码的编写。
    关于#的用法还有很多,希望有兴趣的读者能够留言,我们一起讨论。

    本文出自 “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;

    }

  • 相关阅读:
    Support依赖库大全
    反射调用泛型
    会爬行的小乌龟
    改进版——使用了双缓冲技术
    启动运行发现窗体不能最大化,添加
    添加图层
    实现放大,缩小,漫游,复位等功能
    从上一个项目中我得到的反思
    ​Error -4075: File not found. An error occurred merging module <MODULENAME> for feature <FEATURENAME>.
    总结—angularjs项目
  • 原文地址:https://www.cnblogs.com/kex1n/p/1834600.html
Copyright © 2011-2022 走看看