c - 如何在文件*流中的特定点停止并扫描某些值?

标签 c file while-loop double filestream

我有一个名为 test.txt 的文件,该文件包含:

<this is a test = 1>

<more tests = 42 and more "34">

<start>10.213123 41.21231 23.15323</start>

<random stuff = "4">

<blah 234>

当我看到<start>时我想将后面的 3 个数字扫描成 double ,如下所示:

x = 10.213123
y = 41.21231
z = 23.15323

我有点困惑,因为这里 fgets 扫描整行,我怎样才能将 3 个数字扫描成 double ?因为数字可以有不同的长度?我这样做是为了打印它从文件中读取的内容,但我无法理解它。

void  print_lines(FILE *stream) {
    char line[MAX_LINE_LENGTH];
    while (fgets(line, MAX_LINE_LENGTH, stream) != NULL) {
        fputs(line, stdout);
    }
}

最佳答案

当你看到<start>时然后将3个数字扫描成double。您的行内容位于 line变量,您可以使用 strtod将字符串扫描为 double 。您甚至可以使用sscanf(line, "<start>%lf %lf %lf</start>", &x, &y, &z); ,但使用 strtod 更适合错误处理。

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>

#define MAX_LINE_LENGTH 1024

void  print_lines(FILE *stream) {
    double a, b, c;
    char line[MAX_LINE_LENGTH];
    while (fgets(line, MAX_LINE_LENGTH, stream) != NULL) {
        char *pnt;
        // locate substring `<start>` in the line
        if ((pnt = strstr(line, "<start>") != NULL)) {
            // advance pnt to point to the characters after the `<start>`
            pnt = &pnt[sizeof("<start>") - 1];
            char *pntend;

            // scan first number
            a = strtod(pnt, &pntend);
            if (pnt == pntend) {
                fprintf(stderr, "Error converting a value.\n");
                // well, handle error some better way than ignoring.
            }
            pnt = pntend;
            // scan second number
            b = strtod(pnt, &pntend);
            if (pnt == pntend) {
                fprintf(stderr, "Error converting a value.\n");
                // well, handle error some better way than ignoring.
            }
            pnt = pntend;
            // scan third number
            c = strtod(pnt, &pntend);
            if (pnt == pntend) {
                fprintf(stderr, "Error converting a value.\n");
                // well, handle error some better way than ignoring.
            }

            printf("Read values are %lf %lf %lf\n", a, b, c);
        } else {
            // normal line
            //fputs(line, stdout);
        }
    }
}

int main()
{
    print_lines(stdin);
    return 0;
}

关于c - 如何在文件*流中的特定点停止并扫描某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50874230/

相关文章:

c - Arduino:将十六进制字符串转换为 uint64 或十进制字符串

excel - 将多个 csv 文件合并到一张 Excel 工作表中

c - 尝试打印链接列表时出现段错误

c - 传递结构成员名称以在 C 中运行?

javascript - 如何使用强大的 Node js获取文件扩展名?

php - 使用 PHP 将另一个数据添加到 json 数组

java - 带 Scanner 的 While 循环

javascript - 我正在尝试在 Angular JS 中使用 Javascript 中的循环来打印数组

c - 与另一个启动文件链接

python - 在 python 3.x 中有效地搜索多个文件的关键字的最佳方法?