Hey,
Im having problems converting an integer to a character , it seems to either produce incorrect results when printed(usually some sort of ascii symbols) instead of the actual literal value.

char* str;
str = (char*)malloc(sizeof(char));
snprintf(str, 16, "%d", remainder[i]);
cout << str;

This is what im currently trying, but i tried a number of other ways including a direct cast from int to char, all cause a similar incorrect output, which seems to be their ascii equivelant and not the real value. Can anyone help me or point me in the direction of finding how to convert an integer 9 to char '9' please :)?

That is only allocating one byte of memory! Why???

What is remainder? An array of integers? If that is true you don't need snprintf.. This will work, assuming the value of remainder[i] is < 126.because in C language char is just another int.

char str = remainder[i];
cout << str;

Im writing an integer to hex converter, so im at the point where it converts number > 9 to ABCDEF. So im trying to which iv done, but the 1-9 parts cant be put into the same char array without conversion from int first.
I tried the code you sent, and it seems to display quotations in the command prompt or some other forms of ascii.

cout << remainder[i]; //displays 4, the correct value
    char str = remainder[i]; 
cout << str; // display either ?, S, or "
#include <stdlib.h>
#include <stdio.h>
int main()
{
   int iToHex = 2346;

   printf("%x",iToHex);
   return 0;
}

outputs 92a or if you wish you can sprintf it somewhere

or use unsigned char for value < 255

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
   int iToHex = 255;
   unsigned char pcBuffer[sizeof(iToHex)] = {0};
   memcpy(pcBuffer,&iToHex,sizeof(iToHex));
   printf("[%x][%x][%x][%x]",pcBuffer[0],pcBuffer[1],pcBuffer[2],pcBuffer[3]);
   return 0;
}

cout is not C, it's C++. And it also is less versatile than printf()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.