C++:通过一个点的数据对象转换成字符串的例子来说明整数转化为字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a2013126370/article/details/78086079

通过一个点的数据对象转换成字符串的例子进行阐述,总体的思路是:

  • 一个点的数据对象到字符串的转化过程中需要使用DuplicateString()函数,完成字符串复制的工作。一开始无法确定点转化成字符串占多大字节的存储空间,因为数字转化后,字符串的数据长度是可变的。故先使用缓冲区保存起来,然后再通过DuplicateString()函数从缓存区复制出来。

        知识点总结:
        /*char buf[BUFSIZ];因无法知道所需空间大小,便通过BUFSIZ开辟了系统默认的缓存区大小,需要引入头文件#include <stdio.h>。*/
        /*sprintf函数的格式:int sprintf( char *buffer, const char *format [, argument,...] ),除了前两个参数固定外,可选参数可以是任意个。buffer是字符数组名;format是格式化字符串(像:"=%6.2f%#x%o",%与#合用时,自动在十六进制数前面加上0x)。sprintf函数的返回值是字符数组中字符的个数,即字符串的长度。sprintf与printf函数二者的功能相似,但是sprintf函数打印到字符串中,而printf函数打印输出到屏幕上。sprintf函数在我们完成其他数据类型转换成字符串类型的操作中应用广泛。*/
        char * PtTransformIntoString(PPOINT point)
        {
    
                char buf[BUFSIZ];
                if(point){
                    sprintf(buf, "(%d,%d)", point->x, point->y);
                    return DuplicateString(buf);
                }
                else return "NULL";
        }
    
        char* DuplicateString(const char* s)
        {
                unsigned int n = strlen(s);
                char * t = new char[n+1];
                for(int i=0; i<n; i++)
                    t[i] = s[i];
                t[n] = '\0';
                return t;
        }
    
        int main(){ 
            PPOINT point = PtCreate(3,5);
            char *str = PtTransformIntoString(point);
            cout << str << endl;//输出结果:(3,5)
        }
    

猜你喜欢

转载自blog.csdn.net/a2013126370/article/details/78086079