I have a function that pulls the X,Y,Z co-ords of an accelerometer and stores them in 3 individual integers.
I want to send these via a wireless chip on my microcontroller, but the transmit function takes a string parameter.
So I want to combine the integers into one string and then send this string.
I have:
Int xData;
Int yData;
Int zData;
char totalData[64]
But would like to combine them into a string that is something like this:
("X:" + xData + " Y:" + yData + " Z: "xData)
答案 0 :(得分:2)
Use sprintf
. It works like printf
, but the output is put into a char
array instead of being sento to stdout:
sprintf(totalData, "X:%d: Y:%d: Z:%d", xData, yData, zData);
答案 1 :(得分:2)
Good to prevent buffer overruns. Use snprintf()
and check results.
int n = snprintf(totalData, sizeof totalData, "X:%d Y:%d Z: %d", xData, yData, zData);
if (n >= 0 && n < sizeof totalData) {
Success_SendIt(totalData);
}
Another method that addresses all but the the most pedantic, conservatively "right-size" the buffer and does not use the magic number 64
.
// Longest string length of an int
#include <stdlib.h>
#define INT_STR_LEN (sizeof(int)*CHAR_BIT/3 + 2)
int xData;
int yData;
int zData;
const char format[] = "X:%d Y:%d Z: %d";
char totalData[INT_STR_LEN*3 + sizeof(format) + 1];
sprintf(totalData, format, xData, yData, zData);
SendIt(totalData);
答案 2 :(得分:0)
Write like this:
#include <stdio.h>
int main()
{
int x, y,z;
x=1, y=2, z=3;
char w[6];
sprintf(w, "%d%d%d", x,y,z);
printf(w);
}
change w[i]
size upon your need.