【问题标题】:Parsing a text file with different types in C在 C 中解析具有不同类型的文本文件
【发布时间】:2020-08-02 16:58:52
【问题描述】:

我在解析文本文件时遇到了一些问题。文本的每一行都有一个名称,后跟三个浮点值。所有这些都由一个空格分隔。我想要的是将名称存储在字符串中,将数字存储在数组中。我知道我必须使用 fgets 然后 strtok 阅读每一行,但问题是我不明白 strtok 是如何工作的。我必须四次调用 strtok 吗?如何将每个“片段”分配给我的变量?
感谢您的宝贵时间!

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读the help pages,接受SO tour,阅读How to Ask,以及this question checklist。最后请edit您的问题包括您自己尝试的minimal reproducible example,以及您遇到的问题的描述。
  • 创建一个结构体,例如struct values { char name[32]; float v1, v2, v3; } 然后创建一个 struct values 数组。使用fgets() 读取,然后使用sscanf() 解析。

标签: c parsing


【解决方案1】:

strtok 将在字符串中搜索给定的标记。您必须调用它,直到它返回 NULL。

char *strtok(char *str, const char *delim)

第一次调用通过字符串 (char*) 作为参数 str 完成,其余时间通过 NULL 完成,因为这将定义它应该从该点开始继续寻找下一个令牌。

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

int main()
{
    char line[] = "name 1.45 2.55 3.65";

    char* name;
    double values[3] = { 0 };
    char* ptr = NULL;
    int i = 0;

    ptr = strtok(line, " "); // Search for the first whitespace

    if (ptr != NULL) // Whitespace found
    {
        /* 'line' is now a string with all the text until the whitespace,
           with terminating null character */

        name = calloc(1, strlen(line));
        strcpy(name, line);

        while ((i < 3) && (ptr != NULL))
        {
            ptr = strtok(NULL, " "); // Call 'strtok' with NULL to continue until the next whitespace
            
            if (ptr != NULL) // Whitespace found
            {
                /* 'ptr' has now the text from the previous token to the found whitespace,
                   with terminating null character */
                   
                values[i] = atof(ptr); // Convert to double
            }
            i++;
        }
    }

    printf("%s %lf %lf %lf\n", name, values[0], values[1], values[2]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多