数字转字符串函数

上一篇 / 下一篇  2007-08-15 20:18:30 / 个人分类:Programming

       在应用程序中,经常遇到将数字转字符串的要求.虽然在标准库中有itoa函数,但itoa只能将整数(int)转为字符串.这里给出tostring模板函数,满足一般数字转字符串的要求.示例代码如下.

#include <string>
#include <sstream>
using namespace std;

template <class T>
std::string tostring(T t, std::ios_base & (*f)(std::ios_base&))
{
      std::ostringstream oss;
      oss << f << t; 
     return oss.str();
}


void main()
{
    int v1 = 123;
    float v2 = 123.456;
    double v3 = 123.456;
    string t;

    t = tostring<int>(v1,std::dec); 
   printf(" v1 = %s \n",t.c_str());

    t = tostring<float>(v2,std::dec); 
    printf(" v2 = %s \n",t.c_str());
 
    t = tostring<double>(v3,std::dec); 
   printf(" v3 = %s \n",t.c_str());

   return;
}

运行结果

v1 = 123
v2 = 123.456
v3 = 123.456

 

另外标准函数库中有一些数字和字符、字符串的转换函数,其中gcvt,_gcvt是将浮点数转为字符串的函数,如:

void main()
{
    char ptr[8];
    double a = 1.234;
    gcvt(a,5,ptr);
    printf("a = %s \n",ptr);
}

运行结果
 
a = 1.234

gcvt函数的问题在于,当数字较长时,ptr的字长定义可能不够.这时就会出现运行错误.如
  a = 1.23456789;

程序运行时就会出错误,发生内存崩溃.所以在实用中,使用gcvt还需谨慎.

 


TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar