[英]Access Last Element of Array
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). 我正在尝试访问C ++中数组中的最后一个元素(更具体地说,我正在尝试将整数转换为字符数组,然后访问最后一位)。 Here's what I've come up with 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
. 对于
n
的最后一个十进制数字,请尝试n % 10
。
To get the textual numeral character for that digit, use '0' + (n % 10)
. 要获取该数字的文本数字字符,请使用
'0' + (n % 10)
。
For any other number base, replace 10
with that base. 对于任何其他数字底数,请用该底数替换
10
。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.