因此,我有一个文本文件,其中包含有特定电子邮件的人喜欢的内容:

email1@gmail.com
Likes:
Animals
Sports

email2@gmail.com
Likes:
Science
Animals

我真正需要的是特定用户电子邮件喜欢的特定单词(scanf一次只选择一封电子邮件)和他喜欢的每个主题(所有这些都只是一个单词)将用于我的代码的函数(例如:函数(动物))。
编辑:我只想知道我选择的电子邮件喜欢的每个单词(Case email1我想从文本文件中提取“动物”和“运动”两个单词,因为我需要使用这些单词)。我怎么能用C呢?

最佳答案

尝试下面的代码

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

int main()
{
    FILE * fptr = NULL;
    fptr = fopen("File.txt" , "r");//Let File.txt be the required file
    if(fptr==NULL)//Check if file was opened successfully
    {
        printf("File could not be opened");
        return 0;
    }
    printf("File opened\n");
    char buff[1024];//To store line read from file
    char email[1024];//To store email id
    printf("Enter email id:");
    scanf("%s",email);
    int found=0;
    while(fscanf(fptr,"%[^\n]\n",buff))//Read file line by line and store the line to buff
    {
        //printf(":%s:",buff);

        if(strstr(buff,"@")!=NULL)//Set found=0 if the line in the file is an email id. Here I am checking for the word "@" in the line read since an email id will surely have an @ symbol. Replace it with some checking function to verify if it's an email id
        {
            if(found==1)//If the email was already found break out of the loop
                break;
            found=0;
        }
        if(found==1)//If found=1 buff will have your required Likes including the word Likes:
        {
            if(strcmp("Likes:",buff)!=0)//If required word is not 'Likes:' since only the likes is required not the word 'Likes:'
            {
                printf("%s\n",buff);//buff contains the required like. It can be used as your functions argument.
            }
        }

        if(strcasecmp(email,buff)==0)//Set found=1 if the required email is found
            found=1;
        if(feof(fptr))//Break out of the loop if file end is reached
            break;
    }
}

如果email1是必需的电子邮件id,那么您的输入应该是email1@gmail.com,因为它以这种格式存储在文件中。

10-06 10:28
查看更多