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?
Asked
Active
Viewed 2,030 times
-2

Toon Krijthe
- 52,876
- 38
- 145
- 202

Salman
- 11
- 1
-
what do you mean by "single integer in a single index"? – Sidharth Mudgal Nov 18 '12 at 22:47
-
In a single *element* of a char array? – peterph Nov 18 '12 at 22:47
-
yes in a single element of character array int num; char arr[10]; arr[0]=num; but i am not getting correct value.. – Salman Nov 18 '12 at 22:50
-
Take a look into sprintf() function. Maybe this is what you seek http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/ – Theocharis K. Nov 18 '12 at 22:50
-
What if the integer is `5362`? – SLaks Nov 18 '12 at 22:52
-
4A character is not large enough to store all integers, so what is the range of `num`? – weston Nov 18 '12 at 22:53
-
num is specified to 1 digit only – Salman Nov 18 '12 at 22:56
-
Are you doing the same homework [as this guy](http://stackoverflow.com/q/13445222/596781)? – Kerrek SB Nov 18 '12 at 22:59
-
I assume that you mean 1 **decimal** digit, as oppose to binary, or hex or any other digit. So `num` is in the range `[0..9]` right? If so, you are probably are after doing this: `arr[0]='0' + num` – weston Nov 18 '12 at 23:02
1 Answers
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