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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With