itoa

Jul 2, 2014 at 6:46pm
I'm trying to use itoa method but it won't work here, on c++11.
there is a another way to convert int to const char?
Last edited on Jul 2, 2014 at 6:48pm
Jul 2, 2014 at 7:23pm
Use a stringstream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
#include <cstring>

int main()
{
    char buf[40];

    int m = 456;
    std::ostringstream ss;
    ss << m;
    strcpy(buf, ss.str().c_str());

    std::cout << "buf = " << buf << std::endl;
}
Jul 2, 2014 at 8:18pm
i'm using this on a infinite loop to render a variable on the screen, how can i clear the buffer? and ss?
Jul 2, 2014 at 8:40pm
If you declare the stringstream locally inside the loop, it will always start out empty - unless you use it for several different ints within that loop. Or clear it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>

int main()
{
    int n=123, m = 456;
    
    std::ostringstream ss;  
    ss << m;
    std::cout << ss.str() << std::endl;
    
    ss.str(""); // clear the stringstream
    ss << n;
    std::cout << ss.str() << std::endl;    
}


You don't need to clear the buffer - indeed you may not need it at all, it depends on what it is you are trying to so.
Jul 2, 2014 at 8:45pm
it is working, is rendering the enemy hp value on the screen
thanks.
Topic archived. No new replies allowed.