I want to convert, for example, the number 12 to 0012. So that the number is always 4 characters long. I tried it with this code:
int number;
int result;
void setup() {
number = 12;
Serial.begin(9600);
result = printf("%03d", number);
}
void loop() {
Serial.println(result);
}
However this code outputs only -1 instead of 0012. What is wrong with this code?
答案 0 :(得分:4)
Integers cannot and do not recognize formatting like leading zeros.
The only way to store this type of information would be to use a string (like a char[]
instead of an integer, however it looks like you are simply writing out the value so you shouldn't need a variable for it (as printf()
will handle that for you).
// %04d% will pad your number to 4 digits
printf("%04d", number);
If you do actually need to store your value, you can use sprintf()
and declare your result
as seen below :
int number;
char *result = malloc(5);
and then set it within your setup()
function as such :
sprintf(result, "%04d", number);
Using both of these changes, your updated code might look like :
int number;
char *result = malloc(5);
void setup() {
number = 12;
Serial.begin(9600);
sprintf(result, "%04d", number);
}
void loop() {
Serial.println(result);
}
Consider formatting your values when you are outputting them, otherwise you can use the integer values to perform any arithmetic and calculations with.
答案 1 :(得分:3)
代码的错误在于您正在打印< printf'的返回值。呼叫。它返回打印的字符数。由于看起来stdio尚未设置,因此返回-1作为错误标志。请仔细阅读手册页。
在这一行:
result = printf("%03d", number);
我们想要使用' sprintf'而不是' printf'。
' sprintf的'需要将其输出字符串放在某处。也许预先分配它,确保它大于你的最长输出字符串加一(用于保存终止空字符)。不要在' setup'中分配它,而是将它放在任何例程之外(因为你在一个例程中初始化它,并在另一个例程中使用它)。
char buf[6];
r = sprintf(buf, "%04d", number);
// now print the string inside of 'buf'
Serial.println(buf);