在 C 中将浮点数传递给字符串

Fin*_*ers 2 c string

如何将变量添加到字符串中?我想传输具有实际值的字符串depth。那么如何将其添加到消息中呢?

float depth = ((pressure) / (g)) * 100;
char message[] = "$DBS,,f,depth,M,,,F*hh<CR><LF>";  //Put actual depth here
Run Code Online (Sandbox Code Playgroud)

Kam*_*aze 7

我建议使用snprintf()类似于printf()和建议的用法sprintf(),但是您有一个字符串最大长度的参数。

这样您就可以避免缓冲区溢出。

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

Run Code Online (Sandbox Code Playgroud)

如果字符串会更大,那么您可以通过检查返回值来适应这个数组


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
}
Run Code Online (Sandbox Code Playgroud)

在链接的文章中,您可以找到可用于修改字符串中浮点数格式的说明符和修饰符列表,这非常有用。根据您的数字有多大,您可能想要使用 %e(用于十进制指数表示法或通常称为工程表示法)。此外,您可以影响使用的数字数量和其他内容。真的很值得一看。

或者,您可以查看http://www.cplusplus.com/reference/cstdio/snprintf/http://www.cplusplus.com/reference/cstdio/printf/这对某些人来说更容易理解,但并非如此详细。