Arduino serial.print() 在实际字符后添加一个额外的字符

发布于 2024-10-09 06:50:42 字数 800 浏览 0 评论 0原文

        char *feedtime = "0:0";
        String interval = "6";

    char* convert(char* x, String y){

             int hour;
             int minute;


             sscanf(x, "%d:%d", &hour, &minute);

             char buf[5];

             if (y == "6"){

                 if (hour > 17){

                     hour = (hour+6)%24;

                     snprintf(buf, 5, "%d%s", hour, ":0");

                 }

                 if (hour < 18){

                   hour = hour + 6;
                   snprintf(buf, 5, "%d%s", hour, ":0\0");

                 }

             }

             buf [5] = '\0';
             return buf;
}

当我执行convert(time,interval);时

串行监视器返回正确的值,但会添加 ' 或其他符号。

有什么想法吗?

我根据人们的说法更新了我的代码,但是我仍然遇到同样的问题?

        char *feedtime = "0:0";
        String interval = "6";

    char* convert(char* x, String y){

             int hour;
             int minute;


             sscanf(x, "%d:%d", &hour, &minute);

             char buf[5];

             if (y == "6"){

                 if (hour > 17){

                     hour = (hour+6)%24;

                     snprintf(buf, 5, "%d%s", hour, ":0");

                 }

                 if (hour < 18){

                   hour = hour + 6;
                   snprintf(buf, 5, "%d%s", hour, ":0\0");

                 }

             }

             buf [5] = '\0';
             return buf;
}

When I execute convert(time, interval);

the serial monitor returns the correct value but adds a ' or another symbol to it.

Any ideas why?

I updated my code from what people said, however I still get the same issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拒绝两难 2024-10-16 06:50:42

您正在返回一个指向堆栈变量的指针。这是错误的。一旦函数退出,“buf”使用的堆栈空间就不确定。

You are returning a pointer to a stack variable. This is wrong. Once the function exits the stack space used by 'buf' is undefined.

痴情换悲伤 2024-10-16 06:50:42

您的缓冲区中需要一个额外的字符。您只有 4 个字符的数组,但需要 5 个字符(2 个字符表示小时,2 个字符表示 :0,1 个字符表示尾随 0)。完成后,您还需要以 null 终止字符串。

以及杰科彭哈所说的话。

You need an extra character in your buffer. You only have a 4 character array, but you need 5 characters (2 for the hour, 2 for the :0, and 1 for the trailing 0). You also need to null terminate the string when you are done.

and what jcopenha says.

国粹 2024-10-16 06:50:42

您的字符串没有正确以零结尾。增加buf的大小。

Your strings aren't properly zeroterminated. Increase the size of buf.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文