arrays - 如何从整数数组中减去 1
问题描述
我在学校学习 C,我的项目有点困难。基本上,我正在编写一个获取包含正整数的字符串的函数。该函数从该整数中减去 1 并将获得的值放入字符串中。
所以,如果我有这个;
char nums[] = "2462";
如何编写一个从整数中减去 1 的函数,结果是“2461”?
解决方案
首先,将字符数组转换为整数。
您可以使用atoi
(ASCII to Integer),但因为它在错误时返回 0,所以无法区分成功转换"0"
和错误之间的区别。
而是使用strtol
(STRing TO Long integer)。
// end stores where parsing stopped.
char *end;
// Convert nums as a base 10 integer.
// Store where the parsing stopped in end.
long as_long = strtol(nums, &end, 10);
// If parsing failed, end will point to the start of the string.
if (nums == end) {
perror("Parsing nums failed");
}
现在您可以减去,将整数转回字符串sprintf
,然后将其放入 nums 中。
sprintf(nums, "%ld", as_long - 1);
这并不完全安全。考虑 nums 是否为"0"
. 它只有 1 个字节的空间。如果我们减去 1,那么我们有"-1"
并且我们正在存储 2 个字符,而我们只有 1 的内存。
有关如何安全地执行此操作的完整说明,请参阅如何在 C 中将 int 转换为字符串?.
或者,不要存储它,只需打印它。
printf("%ld", as_long - 1);