-2

I want to store a single integer in a single index of character array. The itoa function is not working in this case. Can anyone help?

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Salman
  • 11
  • 1

1 Answers1

7

If you mean that you want to use the integer as a character value and put it in an array, then it's just

array[index] = number;

If you mean you want to write the value of a single-digit number into a particular index of an array, then

if (number >= 0 && number < 10) {
    array[index] = '0' + number;
} else {
    // not representable by a single digit
}

UPDATE: From your comments, this is probably what you want.

If you mean that you want to write the decimal representation of the number into an array (covering several character elements, not just one), then don't use itoa because that's non-standard and dangerous. snprintf can do that more safely:

if (snprintf(array, array_size, "%d", number) >= array_size) {
    // the array was too small
}

or, since this is C++, you can use std::string to manage the memory for you and ensure the array is large enough:

std::string string = std::to_string(number);

or, if you're stuck with an out-dated C++ library

std::ostringstream ss;
ss << number;
std::string string = n.str();

If you mean something else, then please clarify.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644