【问题标题】:Function with string as return type以字符串为返回类型的函数
【发布时间】:2013-05-30 14:26:48
【问题描述】:

我写了一个函数来巧妙地打印一个浮点值。目前它直接在屏幕上输出它,但在我的代码中的其他地方我需要将此函数的结果存储在一个变量中作为字符串(或 char [])。请问有什么建议吗?

void printfFloat(float toBePrinted)
{
    uint32_t fi, f0, f1, f2;
    char c;
    float f = toBePrinted;

    if (f<0)
    {
        c = '-';
        f = -f;
    }
    else
    {
        c = ' ';
    }

    // integer portion.
    fi = (uint32_t) f;

    // decimal portion...get index for up to 3 decimal places.
    f = f - ((float) fi);
    f0 = f*10;   f0 %= 10;
    f1 = f*100;  f1 %= 10;
    f2 = f*1000; f2 %= 10;
    if(c == '-')
        printf("%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    else
        printf("%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}

这个函数的返回类型应该是什么?我想在最后做类似的事情:

char[32] buffer;
buffer = printfFloat(_myFloat);

【问题讨论】:

  • malloc 足够大的内存块,而sprintf 的值呢?
  • @DanielFischer 你能提供一些代码吗?不知道怎么做。
  • 为什么不直接printf("%.3f", f); 或者我错过了什么?
  • @meaning-matters 显然取负号。这是一个微控制器,它非常愚蠢
  • %dint 值的格式说明符。如果您将参数转换为较小的值,它将无法正确打印。阅读格式说明符,以便获得所需的内容。我经常用%c, '0' + digit来打印一个数字。

标签: c string function char return-type


【解决方案1】:

这个函数的返回类型应该是什么?

C 没有 String 数据类型,因此您必须将缓冲区的地址作为参数传递:

char[32] buffer;
printfFloat(_myFloat, buffer);

你的函数会变成:

void printfFloat(float toBePrinted, char *buffer)
{
   ///rest of code

   if(c == '-')
    sprintf(buffer, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
   else
     sprintf(buffer, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}

【讨论】:

  • 如果你曾经设计过这样的功能,请输入max_len参数,并使用snprintf(buffer, max_len, ...)。否则你只是在乞求一个问题的世界,因为函数可能不知道缓冲区在哪里结束。
【解决方案2】:

看看asprintf,它会为你分配一个缓冲区并填充它。

char *printfFloat(float toBePrinted)
{
    uint32_t fi, f0, f1, f2;
    char c;
    char *ret = NULL;
    float f = toBePrinted;

    if (f<0)
    {
        c = '-';
        f = -f;
    }
    else
    {
        c = ' ';
    }

    // integer portion.
    fi = (uint32_t) f;

    // decimal portion...get index for up to 3 decimal places.
    f = f - ((float) fi);
    f0 = f*10;   f0 %= 10;
    f1 = f*100;  f1 %= 10;
    f2 = f*1000; f2 %= 10;
    if(c == '-')
        asprintf(&ret, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    else
        asprintf(&ret, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    return ret;
}

主要是:

#include <stdio.h>
int main()
{
   char *ret = printfFloat(42.42);
   puts(ret); // print ret
   free(ret);
   return 0;
}

【讨论】:

  • 你能告诉我如何在 main{} 中使用它吗?
  • @nouney,你忘记释放内存了。
  • asprintf 是 GNU 扩展,而不是标准 C 函数。
  • @nouney hmmm asprintf isnt 编译...显然在 stdio.h 中不存在
  • @Saei87 你的操作系统和编译器是什么?
【解决方案3】:

您可以使用sprintffunction

char buffer[32];
sprintf(buffer, "%f", your_float);

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多