8

我正在制作一个由 Arduino 驱动的时钟,在此过程中,我试图将整数格式化为两位数格式的字符串,以便读取时间(例如,将 1 转换为“01”)。

以下给了我“错误:'{'令牌之前的预期主表达式”:

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

我正在尝试按如下方式使用它:

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
}

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

4

3 回答 3

9

花括号语法对变量的初始声明有效,但对事后赋值无效。

此外,您正在返回一个指向自动变量的指针,该变量一旦返回就不再有效分配(并且将被下一次调用破坏,例如 to 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
}
于 2009-11-24T00:50:17.337 回答
1

=在 C 中,您不能使用赋值运算符直接设置数组的内容(您可以初始化一个数组,但这是另一回事,即使它看起来很相似)。

此外:

  • 听起来 Wiringchar(value)功能/操作符不像你想要的那样做;和
  • 如果要返回指向该strOut数组的指针,则必须使其具有静态存储持续时间。

做你想做的事情的简单方法是sprintf

char * formatTimeDigits (int num)
{
  static char strOut[3];

  if (num >= 0 && num < 100) {
    sprintf(strOut, "%02d", num);
  } else {
    strcpy(strOut, "XX");
  }

  return strOut;
}
于 2009-11-24T00:52:44.587 回答
0

几件事:

  • 您不能分配给数组:strOut = {'0', (char)num};
  • 您返回的对象的地址将在 return 语句之后立即停止存在。

对于第一个问题,分配给数组元素:

strOut[0] = '0';
strOut[1] = num;
strOut[2] = '\0';

对于第二个问题,解决方案有点复杂。最好的方法是将目标字符串传递给FormatTimeDigits()函数并让调用者担心它。

FormatTimeDigits(char *destination, int num); /* prototype */
FormatTimeDigits(char *destination, size_t size, int num); /* or another prototype */

第一项还有一点:您可能在初始化中看到过类似的东西。这与赋值不同,它允许与赋值相似的构造。

char strOut[] = {'a', 'b', 'c', '\0'}; /* ok, initialization */
strOut = {'a', 'b', 'c', '\0'}; /* wrong, cannot assign to array */
于 2009-11-24T00:57:33.847 回答