How to convert int to char ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

int main() {
char bought[5]={"0"};
int intbought[5]={2,3,4,5,6};
char *after[]={"0"};

     for(int i=0; i<5; i++){
              
   
     after[i] = itoa(intbought[i], bought, 2);

                  }

}


Main idea is to write int array elements to char array.
I tryed this but it is not working as it should work.
So is there other way to convert?
About three million ways. Here's a few:

http://www.cplusplus.com/articles/numb_to_text/
So, if I understand correctly, you want to write each integer from an integer array into an element in an array of char arrays.

You could statically declare your 'after' array to hold 5 elements, with each element being a char array. Each element should have enough space to hold the largest representation of an int possible:

1
2
3
	// Each char array has enough room for the biggest int,
	// as well as an extra space for the null terminating char
	char after[5][sizeof(int)*8 + 1];


Now this would work if you want to convert the numbers as decimal, but I see you're using a base argument of 2...you want to convert them to binary? If so, you should still be able to statically declare the array with enough room for the largest binary representation of an int.

I don't think you need to use the return value from itoa, it's the same as the 2nd parameter (http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/). So you should just be able to pass in 'after[i]' as the second argument.

Challenge: Once you've sorted that, do it using sprintf instead.

Hope that helps.
Topic archived. No new replies allowed.