gpt4 book ai didi

c - 从字符串 C 中读取一些数据

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

我正在阅读一些包含数据的 .txt 文件。我执行此操作的“策略”只是逐行读取文件。我执行此任务没有任何问题,但是,在某些时候我有一个包含不同数据的字符串(用空格分隔)。我只想读取一些数据,因为我不需要所有数据。我使用 string.h 中的 sscanf 来执行此操作,这是我所拥有的示例:

#include <stdio.h>
#include <string.h>

int main(void) {
char str[] = "1 189.37823 62.18428 2.486 25.33 -21.73 -21.68 -22.01 10.12 10.13 10.11 10.08 9.95 9.89 9.91 7 8.7 0 -42.85";

int id, xid;
double z, r, d, sfr, tmp;
sscanf(str, "%d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&id, &z, &r, &d, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp,
&tmp, &sfr, &xid, &tmp);

printf("id = %d, z = %lf, r = %lf, d = %lf, sfr = %lf, xid = %d\n", id, z, r, d, sfr, xid);
}

但是,我的解决方案非常不优雅,我只是“读取”所有数据,对于我不需要的数据,我使用时间变量。有没有更正确(也许更有效)的方法来做到这一点?

最佳答案

使用%*f读取实际值并将其丢弃。

sscanf(str, "%d %lf %lf %lf %*f %*f %*f %*f %*f %*f %*f %*f %*f %*f %*f %*f %lf %lf %*f",
&id, &z, &r, &d, &sfr, &xid);

关于c - 从字符串 C 中读取一些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32686048/

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