开发者

Access Last Element of Array

开发者 https://www.devze.com 2023-03-30 07:06 出处:网络
I\'m trying to access the last element in an array in C++ (more specifically, I\'m trying to convert an integer into a character array and then access the last digit).Here\'s what I\'ve come up with开

I'm trying to access the last element in an array in C++ (more specifically, I'm trying to convert an integer into a character array and then access the last digit). Here's what I've come up with开发者_StackOverflow中文版 so far:

int number_to_convert = 1234;
char * num_string;
sprintf(num_string, "%d", number_to_convert);
printf("Number: %d Sizeof num_string: %d Sizeof *num_string: %d Sizeof num_string[0]: %d\n", number_to_convert, sizeof(num_string), sizeof(*num_string), sizeof(num_string[0]));

Using this info I tried several different combinations to access the last element:

num_string[sizeof(number_to_convert)/sizeof(*number_to_convert)-1];
num_string[sizeof(number_to_convert)-sizeof(char)]

Maybe there's a better way to get the last digit, but this is the best way I could find. I want the last character (not the null character).


For the last decimal digit of n, try n % 10.

To get the textual numeral character for that digit, use '0' + (n % 10).

For any other number base, replace 10 with that base.


The "because I can" way:

std::ostringstream s;
s << n;
char last_digit = *s.str().rbegin();

Or even:

const char last_digit = *static_cast<std::ostringstream&>(std::ostringstream() << n).str().rbegin();
0

精彩评论

暂无评论...
验证码 换一张
取 消