Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Float into a String in C

Tags:

c

string

How do I add a variable into a string? I want to transmit the string with the actual value of depth. So how do I add this into the message?

float depth = ((pressure) / (g)) * 100;
char message[] = "$DBS,,f,depth,M,,,F*hh<CR><LF>";  //Put actual depth here
like image 257
Finners Avatar asked Mar 19 '26 07:03

Finners


1 Answers

I would suggest to use snprintf() the usage is similar to printf() and the suggested sprintf(), but you have a parameter for max length of the string.

This way you can avoid buffer overflows.

depth = ((pressure)/(g))*100;
char message[100];
snprintf(message, sizeof message, "$DBS,,f,%f,M,,,F*hh\r\n", depth );

if the string would be larger then the array you can accomodate for this by checking the return value


int length = snprintf(message, sizeof message, "$DBS,,f,%f,M,,,F*hh\r\n", depth );

if (length > sizeof message)
{
  //do something to handle if neccessary
}

In the linked article you can find a list of specifiers and modifiers that can be used to modify the format of the float in your string, which can be very useful. Depending on how big your number is you might want to use %e (for decimal exponent notation or often times called engineering notation). Additionally you can influence how many digits are used and other things. It is really worth to check out.

Alternativly you can check out http://www.cplusplus.com/reference/cstdio/snprintf/ and http://www.cplusplus.com/reference/cstdio/printf/ which is easier to understand for some people, but not that in detail.

like image 191
Kami Kaze Avatar answered Mar 21 '26 20:03

Kami Kaze