-1

Sorry if this has been asked before, but I couldn't find anything that helped my situation. I'm trying to assign an integer to an index in a char array. In this case, assigning 33 into an index of the token array.

char token[100];
int num = 33;
//Assigning num to this place in array
token[1] = num; //How do I make this work?

I want 33 to be an index in the token array, yet when I assign it and print it out it gives me '!', which is the ASCII value for 33. I want to convert the num to a string and then assign it to the index. So how would I convert num to a string and then assign it to the token array?

madaniloff
  • 55
  • 8

1 Answers1

1

If you meant, that you have a pointer, that points to a char array, you can do this.

char* token = new char[100];
    token[0] = 33; // You actually get '!' since char 33 is indeed '!'
std::cout << (int)token[0] << std::endl; // cast it to an int, 33 is back

If you want to use an array of char pointers, you can do this:

char* token[100];
char* temp = new char; // You need a char* to store it since char is 1byte and int is 4byte
    *temp = 33; // or *temp = num; in your case
    token[0] = temp; // You still get '!' since char 33 is indeed '!'
std::cout << (int)*token[0] << std::endl; // cast it to an int
Onyrew
  • 136
  • 7