1

I trying to merge all members of a float array in a char array.

This is float array :

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

And this is char array :

char myCharArray[32];

I want to set char array like "1020"

in C# i can do it like this;

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

but how can i do this in C?

  • The line `string myStr = myFloatArray[0] + myFloatArray[1];` [will not compile in C#](https://godbolt.org/z/YPKcxehvn). Do you mean `string myStr = myFloatArray[0].ToString() + myFloatArray[1].ToString();`? – Andreas Wenzel Jan 21 '23 at 14:15
  • MBK Software, How would you want `{1,20}` and `{12,0}` to print out? Or `{1,2,3}` vs. `{123};` vs. `{12. 30, 0};`? – chux - Reinstate Monica Jan 22 '23 at 01:36

2 Answers2

2

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:

1020
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • I would do just `%.0f`. – KamilCuk Jan 21 '23 at 13:16
  • @KamilCuk: Yes, you are correct. That solution is much simpler. Thanks for pointing it out. I have taken it over. – Andreas Wenzel Jan 21 '23 at 13:24
  • @MBKSoftware: In my example above, `myCharArray[0]` has the value `'1'`, because that is the first character of the string `"1020"`. What makes you think that it has the value "null"? – Andreas Wenzel Jan 21 '23 at 14:06
  • @MBKSoftware: As you can see in [this demonstration](https://godbolt.org/z/rvaPoexj3), `myCharArray[0]` has the value `49`, which is the ASCII character code for the digit `1`. Therefore, as far as I can tell, my solution is correct. – Andreas Wenzel Jan 21 '23 at 14:21
1

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. The "%.0f" format specifier tells sprintf to format the float value as an 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(myCharArray, sizeof(myCharArray), "%.0f", myFloatArray[0]);
snprintf(myCharArray+strlen(myCharArray), sizeof(myCharArray)-strlen(myCharArray), "%.0f", myFloatArray[1]);