Arduino字符串格式问题

amb*_*800 8 c string format arduino

我正在制作一个Arduino供电的时钟,在这个过程中,我正在尝试将整数格式化为两位数字格式的字符串,以便读出时间(例如1变为"01").

以下给出了"错误:'{'token'之前的预期primary-expression:

char * formatTimeDigits (int num) {
  char strOut[3] = "00";
  if (num < 10) {
    strOut = {'0', char(num)};
  }
  else {
    strOut = char(num);
  }
  return strOut;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用它如下:

void serialOutput12() {
  printWeekday(weekday); // picks the right word to print for the weekday
  Serial.print(", "); // a comma after the weekday
  Serial.print(hour12, DEC); // the hour, sent to the screen in decimal format
  Serial.print(":"); // a colon between the hour and the minute
  Serial.print(formatTimeDigits(minute)); // the minute
  Serial.print(":"); // a colon between the minute and the second
  Serial.print(formatTimeDigits(second)); // the second
}
Run Code Online (Sandbox Code Playgroud)

关于我在这里缺少什么的想法?

Jef*_*tin 9

大括号语法对于变量的初始声明有效,但在事后不能用于赋值.

此外,您将返回一个指向自动变量的指针,该变量在返回后不再有效分配(并且将在下一次调用时被粉碎,例如print).你需要做这样的事情:

void formatTimeDigits(char strOut[3], int num)
{
  strOut[0] = '0' + (num / 10);
  strOut[1] = '0' + (num % 10);
  strOut[2] = '\0';
}

void serialOutput12()
{
  char strOut[3]; // the allocation is in this stack frame, not formatTimeDigits

  printWeekday(weekday); // picks the right word to print for the weekday

  Serial.print(", "); // a comma after the weekday

  Serial.print(hour12, DEC); // the hour, sent to the screen in decimal format

  Serial.print(":"); // a colon between the hour and the minute

  formatTimeDigits(strOut, minute);
  Serial.print(strOut); // the minute

  Serial.print(":"); // a colon between the minute and the second

  formatTimeDigits(strOut, second);
  Serial.print(strOut); // the second
}
Run Code Online (Sandbox Code Playgroud)