如何在没有sprintf()的情况下将long转换为字符串?

时间:2013-03-30 12:48:13

标签: c++ linux compilation printf

我需要将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 个答案:

答案 0 :(得分:2)

我认为你可以使用stringstream。

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

(x.str()。c_str()使它成为char *) 它对我有用。

答案 1 :(得分:1)

您可以使用stringstream

示例:

#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;
}

答案 2 :(得分:0)

您应该利用像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

答案 3 :(得分: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;
  }