簡體   English   中英

解析C中不同類型的文本文件

[英]Parsing a text file with different types in C

我在解析文本文件時遇到了一些麻煩。 文本的每一行都有一個名稱,后跟三個浮點值。 所有這些都由一個空格分隔。 我想要的是將名稱存儲在字符串中,將數字存儲在數組中。 我知道我必須使用 fgets 然后 strtok 閱讀每一行,但問題是我不明白 strtok 是如何工作的。 我必須四次調用 strtok 嗎? 如何將每個“片段”分配給我的變量?
感謝您的時間!

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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM