简体   繁体   中英

How to store an integer in a single index of character array?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM