访问数组的最后一个元素

syl*_*syl 1 c++ arrays element

我正在尝试使用C++访问数组中的最后一个元素(更具体地说,我正在尝试将整数转换为字符数组,然后访问最后一个数字).这是我到目前为止所提出的:

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]));
Run Code Online (Sandbox Code Playgroud)

使用此信息,我尝试了几种不同的组合来访问最后一个元素:

num_string[sizeof(number_to_convert)/sizeof(*number_to_convert)-1];
num_string[sizeof(number_to_convert)-sizeof(char)]
Run Code Online (Sandbox Code Playgroud)

也许有更好的方法来获得最后一位数,但这是我能找到的最佳方式.我想要最后一个字符(不是空字符).

Ker*_* SB 9

对于最后一个十进制数字n,请尝试n % 10.

要获取该数字的文本数字字符,请使用'0' + (n % 10).

对于任何其他数字基数,请替换10为该基数.


"因为我可以"的方式:

std::ostringstream s;
s << n;
char last_digit = *s.str().rbegin();
Run Code Online (Sandbox Code Playgroud)

甚至:

const char last_digit = *static_cast<std::ostringstream&>(std::ostringstream() << n).str().rbegin();
Run Code Online (Sandbox Code Playgroud)