Arduino字符串格式问题

时间:2009-11-24 00:46:02

标签: 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;
}

我正在尝试使用它如下:

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
}

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

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:1)

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

此外:

  • 听起来不像接线char(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;
}

答案 2 :(得分: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 */
相关问题