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?
            Asked
            
        
        
            Active
            
        
            Viewed 66 times
        
    1
            
            
         
    
    
        Mohit Kanwar
        
- 2,962
- 7
- 39
- 59
 
    
    
        John Lui
        
- 1,434
- 3
- 23
- 37
- 
                    3`std::stringstream` doesn't require c++11. – πάντα ῥεῖ Jul 31 '15 at 06:20
- 
                    Doesn't the usage of `<<` requires C++11? – John Lui Jul 31 '15 at 06:23
- 
                    No it doesn't require c++11. – πάντα ῥεῖ Jul 31 '15 at 06:25
3 Answers
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;
}
 
    
    
        Soner from The Ottoman Empire
        
- 18,731
- 3
- 79
- 101
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
- 
                    
- 
                    1It 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