Raulp
Raulp

Reputation: 8156

Making a whole argument as string containing float values in C

I am tying to pass a whole string to a method where the string contains the float values as well e.g

 float ac_current ;
    char ac_current_char [MAX];
    
    ac_current = my_method()
    gcvt(ac_current , 6, ac_current_char );
  
    printf("current is: %s\n", ac_current_char );

This works fine , but I want a single string containing :

 "current is: %s\n", ac_current_char 


e.g current is 1.3422 

How this can be done?

Upvotes: 2

Views: 71

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117408

You are using

gcvt - convert a floating-point number to a string

#include <stdlib.h>
char *gcvt(double number, int ndigit, char *buf);

and this function doesn't check the boundary of buf so I wouldn't use it. Check if there's a version that does bounds checking, or create your own:

char *mygcvt(double number, int ndigit, char *buf, size_t size) {
    // return NULL if there's not enough room
    if(snprintf(buf, size, "%.*g", ndigit, number) >= size) return NULL;
    return buf;
}

Then use it to populate the char[] array:

int main() {
    float ac_current;
    char ac_current_buf[MAX];
    
    ac_current = my_method();
    char* ac_current_char = mygcvt(ac_current, 6, ac_current_buf, MAX);
    
    if(ac_current_char == NULL) { // check that the conversion actually worked
        puts("the conversion requires a bigger buffer");

    } else {
        char ac_current_str[TOTALMAX];

        if(TOTALMAX <= snprintf(ac_current_str, TOTALMAX,
                                "current is: %s\n", ac_current_char))
        {
            puts("the whole string wouldn't fit");
        } else
        {   // success
            puts(ac_current_str);
        }        
    }
}

The floating point conversion and putting it into a string could however be simplified by combining the two by skipping the gcvt step:

int main() {
    float ac_current;

    char ac_current_char[MAX];
    ac_current = my_method();
        
    if(snprintf(ac_current_char, MAX, "current is: %.*g\n", 6, ac_current) >= MAX)
    {
        puts("the whole string wouldn't fit");
    } else
    {   // success        
        puts(ac_current_char);
    }        
}

Upvotes: 2

Related Questions