0

我需要将 long 转换为字符串,但我不能使用sprintf().

这是我的代码

char *ultostr(unsigned long value, char *ptr, int base)
{
    unsigned long t = 0; 
    unsigned long res = 0;
    unsigned long tmp;
    int count = 0;

    tmp = value;

    if (ptr == NULL)
    {
        return NULL;
    }

    if (tmp == 0)
    {
        count++;
    }

    while(tmp > 0)
    {
        tmp = tmp/base;
        count++;
    }

    ptr += count;
    *ptr = '\0';

    do
    {
        t = value / base;
        res = value - (base*t);

        if (res < 10)
        {
            * -- ptr = '0' + res;
        }
        else if ((res >= 10) && (res < 16))
        {
            * --ptr = 'A' - 10 + res;
        }

        value = t;
    } while (value != 0);

   return(ptr);
}
4

4 回答 4

2

You could use stringstream I think.

#include <sstream>
...
std::stringstream x;
x << 1123;
cout << x.str().c_str();

(x.str().c_str() makes it char*) it worked for me.

于 2013-03-30T12:55:27.793 回答
1

You can use stringstream.

Example:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    ostringstream ss;
    long i = 10;
    ss << i;
    string str = ss.str();
    cout << str << endl;
}
于 2013-03-30T12:52:41.440 回答
0
 #include<iostream>
 #include<string>
 #include<sstream>

 int main(int argc, char *argv[])
  {
    unsigned long d = 1234567;
    std::stringstream m_ss;
    m_ss << d;
    std::string my_str;
    m_ss >> my_str;
    std::cout<<my_str<<std::endl;

    return 0;
  }
于 2013-03-31T11:59:16.973 回答
0

You should take advantage of stream objects like std::stringstream:

#include <string>
#include <sstream>

int main()
{
    long int i = 10000;

    std::stringstream ss;
    std::string str;

    ss << i;

    str = ss.str();

    std::cout << str; // 10000
}

Live Demo

于 2013-03-30T12:52:21.207 回答