简体   繁体   English

浮点到C中的char数组

[英]Float to char array in C

I trying to merge all members of a float array in a char array.我试图将 float 数组的所有成员合并到 char 数组中。

This is float array:这是浮点数组:

float myFloatArray[2] = {10,20};

And this is char array:这是 char 数组:

char myCharArray[32];

I want to set char array like "1020"我想设置像“1020”这样的字符数组

in C# i can do it like this;在 C# 我可以这样做;

string myStr =  myFloatArray[0] + myFloatArray[1];

but how can i do this in C?但是我怎么能在 C 中做到这一点呢?

If you only have two numbers to be converted, then you can simply write如果你只有两个数字要转换,那么你可以简单地写

snprintf(
    myCharArray, sizeof myCharArray,
    "%.0f%.0f",
    myFloatArray[0],
    myFloatArray[1]
);

Here is a working example program:这是一个工作示例程序:

#include <stdio.h>

int main(void)
{
    float myFloatArray[2] = {10,20};
    char myCharArray[32];
    snprintf(
        myCharArray, sizeof myCharArray,
        "%.0f%.0f",
        myFloatArray[0],
        myFloatArray[1]
    );

    printf( "%s\n", myCharArray );
}

This program has the following output:该程序具有以下 output:

1020

A simple way is to use sprintf to convert the first and second elements of the float array to strings, and concatenate them into the char array.一种简单的方法是使用sprintf将float数组的第一个和第二个元素转换为字符串,并将它们拼接成char数组。 The "%.0f" format specifier tells sprintf to format the float value as an integer. “%.0f”格式说明符告诉 sprintf 将浮点值格式化为 integer。

sprintf(myCharArray, "%.0f%.0f", myFloatArray[0], myFloatArray[1]);

Also notice the answer provided in this post where snprintf is suggested for safety reasons.另请注意这篇文章中提供的答案,出于安全原因建议使用snprintf

snprintf(myCharArray, sizeof(myCharArray), "%.0f", myFloatArray[0]);
snprintf(myCharArray+strlen(myCharArray), sizeof(myCharArray)-strlen(myCharArray), "%.0f", myFloatArray[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM