我正在尝试从DateTime
实例将一个月的某天写入TFT显示。 DateTime
实例的数据来自RTC。
基本上,我正在尝试这样做:
DateTime timenow;
timenow = rtc.now(); // Get and store the current RTC data as DateTime.
tft.textWrite(timenow.day()); // This doesn't work (see below), but it shows the idea of what I am trying to do.
tft.textWrite
接受char
作为其参数,但是timenow.day()
似乎输出int
。我能够使它工作的唯一方法(显然,这不是一个好方法,正如您将看到的那样)是通过将从1到31的所有数字作为char
组成一个巨大的数组:const char days[31][3] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
然后我在代码中使用了数组:
DateTime timenow;
timenow = rtc.now(); // Get and store the current RTC data as DateTime.
tft.textWrite(days[timenow.day() - 1]);
不幸的是,这一年我必须做同样的事情,而且我无法在可预见的将来将所有年份手动输入到数组中。这将占用内存,此外,这将不必要地耗时。
我的问题是,有人可以告诉我如何从
int
转换为char
以便在此函数中使用,而无需庞大的数组? 我已经尝试了从
String(timenow.day())
到char(timenow.day())
到char(String(timenow.day()))
之类的所有东西,但它们似乎都不起作用。
最佳答案
您需要将整数转换为字符串。
int day = timenow.day();
char str[12];
sprintf(str, "%d", day);
tft.textWrite(str);
编辑:
代码说明:
timenow.day()
的整数值存储到day
中; char
数组,以存储int day
到char. It will be used in the
的转换sprintf()function call. This char array must be big enough to hold the conversion string. So that is why I used
char str [12]`。因此,我们有12个字节来存储转换后的值。 sprintf(str, "%d", day)
将char *
作为其存储转换的第一个参数。第二个参数是要获取的输出字符串的格式。然后,下一个参数是您传递的格式字符串所需的参数,在这种情况下,它是"%d"
,这意味着我们需要为其提供一个整数值。这就是为什么我们将day
变量作为最后一个参数传递的原因。 您可以通过在Linux终端中运行
sprintf
来获得man sprintf
功能的更多详细信息。否则,您可以获得更多信息here。
关于c++ - 在TFT上显示日期而不使用char形式的数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61108757/