c - 如何在 C 中使用 Pebble SDK 将 int 转换为字符串

标签 c string int pebble-watch pebble-sdk

刚拿到我的 Pebble,我正在试用 SDK。我是 C 的新手,但我知道 Objective-C。那么有没有办法创建这样的格式化字符串?

int i = 1;
NSString *string = [NSString stringWithFormat:@"%i", i];

而且我不能使用 sprintf,因为没有 malloc

我主要想用 text_layer_set_text(&countLayer, i); 显示一个 int

最佳答案

使用snprintf()用整数变量的值填充字符串缓冲区。

/* the integer to convert to string */
static int i = 42;

/* The string/char-buffer to hold the string representation of int.
 * Assuming a 4byte int, this needs to be a maximum of upto 12bytes.
 * to hold the number, optional negative sign and the NUL-terminator.
 */
static char buf[] = "00000000000";    /* <-- implicit NUL-terminator at the end here */

snprintf(buf, sizeof(buf), "%d", i);

/* buf now contains the string representation of int i
 * i.e. {'4', '2', 'NUL', ... }
 */
text_layer_set_text(&countLayer, buf);

关于c - 如何在 C 中使用 Pebble SDK 将 int 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20435527/

相关文章:

c - C中是否允许负数组索引?

c - 错误: control may reach end of non-void function

C - 如何保持变量

python - 在 python 中使用 str.format() 女巫类

java - 在 Java 中将 boolean 值转换为整数

dart - 如何在 dart/flutter 中声明 64 位无符号整数?

c - 使用strtod后如何将double值转换为char数组?在C中

c++ - 贪婪地分配分数以最大化最终结果

c - !s || 是什么意思!* 是什么意思? (s 是字符*)

c++ - 坏指针 : expression can not be evaluated while parsing tokens