How to format an integer as 3 digit string? If I give 3 formated string should be 003
printf("%03d\n", 3); // output: 003
This doesn't work in Arduino.
How to format an integer as 3 digit string? If I give 3 formated string should be 003
printf("%03d\n", 3); // output: 003
This doesn't work in Arduino.
The standard C function printf print to stdout. Arduino doesn't has a stdout. You can print to Serial, but must prepare/format the string first.
Instead of printf, use snprintf. It prints to a char array, which you later can use with Serial.print, or whatever other function that take a string.
void setup() {
Serial.begin(9600);
while(!Serial);
char buffer[4];
snprintf(buffer,sizeof(buffer), "%03d", 3);
Serial.println(buffer);
}
void loop() {
}
Note: all the comments apply to this answers.
sprintfwith achararray buffer and then pass it toSerial.print(). – jfpoilpret Feb 21 '17 at 16:51char buff[4]as you need one byte for the terminating zero that will be added bysprintf. If you don't, it may overwrite some value in your stack, leading to hard to understand problems. – jfpoilpret Feb 21 '17 at 17:12printf()to print throughSerial. This way you don't have to allocate room forsprintf(), which can be (as you just experienced) error prone. – Edgar Bonet Feb 21 '17 at 18:10buffer[7]you can safely print anyint, and withbuffer[12]you can print anylong. – Edgar Bonet Feb 21 '17 at 20:53