1

I have been trying to convert a number to a string. But the only problem is, I cannot use C++11. I know their exists functions such as to_string and sstream but all of them require C++11. Is their any other way I can do it?

Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59
John Lui
  • 1,434
  • 3
  • 23
  • 37

3 Answers3

2

It is conversation a number to a string in C++03. String streams helpful for it.

#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

You can use sprintf from the C standard library:

#include <cstdio>
...
int i = 42;
char buffer[12]; // large enough buffer
sprintf(buffer, "%d", i);
string str(buffer);
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • http://ideone.com/4rgJSP. I don't know why but it says that `itoa` is out of scope here. – John Lui Jul 31 '15 at 06:28
  • @JohnLui Oops, my mistake, `itoa` is actually non-standard in C++ and only supported by some compilers, use `sprintf` instead. – Emil Laine Jul 31 '15 at 06:31
0

Maybe try to add number to string?

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

Hope this help.

Andret2344
  • 653
  • 1
  • 12
  • 33
  • Can it compile? If yes, then, what is the result? – Andret2344 Jul 31 '15 at 06:30
  • 1
    It compiles, but it doesn't do the right thing. Concatenation with `+` is not supported on C-strings (`""` is a C-string). Instead it decays the `""` to a pointer of type `const char*`, and then does pointer arithmetic on that pointer, offsetting it by `a * sizeof(char)`, so the pointer points outside the C-string, thus resulting in undefined behavior. – Emil Laine Jul 31 '15 at 06:38