• 如何将数字(包括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;

    }

  • 相关阅读:
    算法学习:二分法从入门到精通
    TypeScript筑基笔记一:Visual Studio Code 创建Typescript文件和实时监控
    LeetCode 92. 反转链表 II
    LeetCode 1525. 字符串的好分割数目
    字节跳动-people后台一面面经
    LeetCode 117. 填充每个节点的下一个右侧节点指针 II
    LeetCode 1529. 灯泡开关 IV
    LeetCode 165. 比较版本号
    LeetCode 312. 戳气球
    LeetCode 605. 种花问题
  • 原文地址:https://www.cnblogs.com/kex1n/p/1834600.html
Copyright © 2020-2023  润新知