簡體   English   中英

如何在 C 中使用 fscanf 從 txt 文件中讀取類似數據的句子?

[英]How to read sentence like data from txt file using fscanf in C?

我目前在從 C 中的 txt 文件讀取數據時遇到問題。文件中數據的結構是這樣的:

邁克今年 26 歲,住在加拿大。

我想從使用 fscanf 列出的數據中獲取姓名、年齡和國家

如果所有句子都具有相同的模式,您可以逐行閱讀文本並將該行拆分為單詞。 您可以使用以下代碼執行此操作:

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

int main(int argc, char *argv[])
{
    FILE * database;
    char buffer[100];

    database = fopen("test.txt", "r");

    if (NULL == database)
    {
        perror("opening database");
        return (-1);
    }

    while (EOF != fscanf(database, "%[^\n]\n", buffer))
    {
        printf("> %s\n", buffer);
        char * token = strtok(buffer, " ");
         
        while (token != NULL) 
        {
            //First token is the name , third token is the age etc..
            printf( " %s\n", token );//printing each word, you can assign it to a variable
            token = strtok(NULL, " ");  
        }
    }

    fclose(database);

    return (0);
}

對於 fscanf() 我使用以下帖子,您也可以檢查它: Traverse FILE line by line using fscanf

當您從句子中取出每個單詞時,您可以將其分配給變量或根據需要處理它

暫無
暫無

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

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