繁体   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