gpt4 book ai didi

c - 将浮点变量中的逗号分隔字符串写入串行端口

转载 作者:行者123 更新时间:2023-11-30 17:20:43 24 4
gpt4 key购买 nike

我正在解析一个字符串,其中包含 3 个值,以逗号分隔。我目前正在使用 sscanf 来实现此目的,效果很好。我想做的是在解析字符串后对这些值进行操作,并将结果连接回我收到的相同格式,并在每次读取和操作字符串后将其写回到串行端口。我认为我遇到的问题是我在解析时将变量声明为 float ,并且想知道如何将 float 放回一起以写入串行端口。我还遇到变量实际写入缓冲区并发送出去的问​​题,但这是一个不同的故事。任何对此的帮助将不胜感激。这是我所拥有的示例:

    do {
struct timeval timeout = {0,299500};
char c;
fd_set fds;
int ret1, ret2;
//Zero file descriptor set, then append all types.
FD_ZERO(&fds);
FD_SET(cmp_fd, &fds);
FD_SET(STDIN_FILENO, &fds);
ret1 = select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
if (ret1 == -1)
{
perror("select");
need_exit = 1;
}
else if (ret1 > 0)
{
if (FD_ISSET(cmp_fd, &fds))
{
do {ret2 = read(cmp_fd, &c, 1);}
while ((ret2 < 0 && errno == EINTR));
if (ret2 == 1)
{
data_str[cmp_ind] = c;
cmp_ind++;

if(c == '\n')
{
float press, temp, cond;
char strn;

int asdf = sscanf(data_str,"%f,%f,%f", &press, &temp, &cond);
strn = ("%f,%f, %f", press, temp, cond);

char ppri[3]
ppri[1]= [press+1.3,temp,cond];
ppri[2] = temp;
ppri[3] = cond;
printf("%f",ppri);

write(cmp_fd,ppri,sizeof(ppri)); /* <-- This is what I am trying to do*/
/*needed output is: "#####.##,#####.##, #####.##" */
bzero(data_str,100);
cmp_ind = 0;
printf("\r\n");

}
}
else if(ret2 == -1)
{
perror("read");
need_exit = 1;
}
}
if(FD_ISSET(STDIN_FILENO, &fds))
{
do {ret2 = read(STDIN_FILENO, &c, 1);}
while (ret2 < 0 && errno == EINTR);
if(ret2 == 1)
{
if(c == '\x01') {
need_exit = -1;
}
}
}
}

}
while (!need_exit);

最佳答案

int asdf = sscanf(data_str,"%f,%f,%f", &press, &temp, &cond);
strn = ("%f,%f, %f", press, temp, cond);

我认为上面您可能想用所有三个浮点变量形成一个字符串,但是,这实际上是将cond浮点值转换为strn中的字符

char ppri[3]

ppri 是一个 3 个字符的数组,在将三个浮点值转换为字符串后,它实际上无法存储它们,除非每个浮点都是一位整数。但仍然没有空间在其中放置三个逗号。

ppri[1]= [press+1.3,temp,cond];

这条线不会不惜一切代价编译,我不知道它是如何为你编译的。

ppri[2] = temp;
ppri[3] = cond;

声明了大小为 3 的 char 数组,您无法访问 ppri[3],数组索引从 0 开始。

printf("%f",ppri);

由于 ppri 是一个数组,因此 ppri 存储第一个字符的地址。

write(cmp_fd,ppri,sizeof(ppri)); 

这将在 fd 指向的文件中写入 3 个字符。

我不确定你在这部分代码中想要做什么,这是我的初步观察,你可以看到代码中的其他错误,尝试修复它们。

但无论如何,如果你想解析以逗号分隔的 float ,那么你可以使用,

float f1, f2, f2;
// read float values from string,
sscanf(data_str,"%f,%f,%f",&f1,&f2,&f3);
// modify the float value
f1 += 10;
// form the modified string again.
sprintf(data_str,"%f,%f,%f",f1,f2,f3);

并写回data_str

关于c - 将浮点变量中的逗号分隔字符串写入串行端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28459543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com