gpt4 book ai didi

c++ - 在TFT上显示日期而不使用char形式的数字数组

转载 作者:行者123 更新时间:2023-12-02 10:34:05 24 4
gpt4 key购买 nike

我正在尝试从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 daychar. 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com