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?

2
  • The line string myStr = myFloatArray[0] + myFloatArray[1]; will not compile in C#. Do you mean string myStr = myFloatArray[0].ToString() + myFloatArray[1].ToString();? Commented Jan 21, 2023 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};? Commented Jan 22, 2023 at 1:36

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

I would do just %.0f.
@KamilCuk: Yes, you are correct. That solution is much simpler. Thanks for pointing it out. I have taken it over.
@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"?
@MBKSoftware: As you can see in this demonstration, 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.
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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.