Reputation: 21
I have to convert an int to an ASCII string. Basically, i want this :
int iTest = 128;
char ca[3];
??? --> **SOLUTION :** sprintf(ca,"%d",iTest);
and the result :
ca[0] = 0x31;--> Hexcode of '1'
ca[1] = 0x32;
ca[2] = 0x38;
Upvotes: 0
Views: 6574
Reputation: 56529
Use std::string
and std::to_string
:
#include <string>
#include <iostream>
using namespace std;
...
int iTest = 128;
string ca = to_string(iTest);
for (int i = 0; i < ca.size(); i++)
{
cout << hex << "0x" << (int) ca[i] << endl;
}
Result:
0x31
0x32
0x38
Upvotes: 1
Reputation: 409432
Use the modulo and division operators to get each digit, then print each digit adding '0'
.
Upvotes: 0
Reputation: 38173
for each digit
ca[ i ] = digit + '0';
Notes:
ca
dynamically, based on the "length" of the number (the number of digits)%
and /
operators for modulo and division.Upvotes: 0