将数字转换为字符串的任何替代方法?

时间:2015-07-31 06:18:33

标签: c++

我一直在尝试将数字转换为字符串。但唯一的问题是,我不能使用C ++ 11。我知道它们存在的函数,例如to_stringsstream,但它们都需要C ++ 11。他们可以用其他任何方式做到吗?

3 个答案:

答案 0 :(得分:2)

对话是 C ++ 03 中字符串的数字。字符串流对它有帮助。

#include <iostream>
#include <string>
#include <sstream>  //include this to use string streams

using namespace std;

int main()
{
    int number = 1234;
    double dnum = 12.789;

    ostringstream ostr1,ostr2; //output string stream
    ostr1 << number; //use the string stream just like cout,
    //except the stream prints not to stdout but to a string.

    string theNumberString = ostr1.str(); //the str() function of the stream
    //returns the string.

    //now  theNumberString is "1234"

    cout << theNumberString << endl;

    // string streams also can convert floating-point numbers to string
    ostr2 << dnum;
    theNumberString = ostr2.str();
    cout << theNumberString << endl;

    //now  theNumberString is "12.789"

    return 0;
}

答案 1 :(得分:1)

您可以使用C标准库中的sprintf

#include <cstdio>
...
int i = 42;
char buffer[12]; // large enough buffer
sprintf(buffer, "%d", i);
string str(buffer);

答案 2 :(得分:0)

也许尝试将数字添加到字符串?

int a = 10;
string s = a + "";

希望得到这个帮助。