繁体   English   中英

如何从 txt 文件中读取数据并忽略我不想要的值,直到达到某个阈值?

[英]How can I read data from a txt file and ignore values I don't want until a certain threshold is met?

我的任务是从 txt 文件中读取数据,该文件在 2 个长列中具有值。 右侧是时间,左侧是电压电平。 txt 文件的示例如下所示:

0.000000     -0.031960
0.000977      0.076080
0.001953      0.089640
0.002930      0.065460
0.003906      0.083060
0.004883     -0.074380
0.005859      0.092880
0.006836      0.027440
0.007812      0.058540
0.008789      0.026980
0.009766     -0.082800
0.010742      0.049660
0.011719      0.003560
0.012695      0.046220
0.013672      0.063120
0.014648      0.016040
0.015625      0.030760

我想读取这个文件并忽略所有数据,直到我遇到高于 0.5 的电压(右侧)。 然后输出满足另一个阈值的值,直到文件结束。

我已经开始我的代码读取文件,但我只是不知道我将如何读取数据并仅在达到阈值时输出数据。

这是我到目前为止所做的:

#include <stdio.h>
#define MAXCHAR 1000

int main() {
 FILE *fp;
    char str[MAXCHAR];
    char* filename = "test1.txt";
 
    fp = fopen(filename, "r");
    if (fp == NULL){
        printf("Could not open file %s",filename);
        return 1;
    }
    while (fgets(str, MAXCHAR, fp) != NULL)
    if ()
        printf("%s", str);
    fclose(fp);
    return 0;
}

这可能会有所帮助。 我更改了此中第一个阈值的值以进行测试(您的数据集没有任何超过 0.5 的电压...)

#include <stdio.h>
#define MAXCHAR 1000

int main() {
    double thres_1 = 0.08;
    FILE *fp;
    char str[MAXCHAR];
    char* filename = "test1.txt";

    fp = fopen(filename, "r");
    if (fp == NULL){
        perror("Could not open file ");
        return 1;
    }
    int tmet = 0;
    while (fgets(str, MAXCHAR, fp) != NULL) {
        float t, v;
        if (sscanf(str, "%g%g", &t, &v) == 2) {
            if (v >= thres_1) {
                tmet = 1;
            }
            if (tmet) {
                printf("%f\t%f\n", t, v);
            }
        }
    }
    if (!tmet) {
        printf("Threshold was never exceeded");
    }
    fclose(fp);
    return 0;
}

“第二个阈值”以及达到时要做什么,并没有真正指定,但是您可以构建更多代码来检测它并在循环内执行其他操作。

在此(不正确)声明之前;

if ()

代码需要从当前输入行中提取两个值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM