使用strtok分隔字符串并存储在struct中

use strtok to separate string and store in struct

我想我应该改一下我的问题。我的结构如下:

struct profile {
    char name[30];
    int age, phoneNo;
};

我有一个包含如下字符串的文件:

James Brown,35y,0123456789
Mary Brown,45y,0123987456

目前我已经编写了一个代码来使用此人的 name/age/phoneNo 搜索记录,我想将记录存储到我拥有的结构中。我正在尝试使用 strtok 将数据与逗号分开,但我的代码不起作用。

int main()
{
    char search[50];
    char record[50];
    const char s[2] = ",";
    char* token;
    struct profile c;

    FILE* fPtr;
    if (fPtr = fopen("profile.txt", "r"))
    {
        // flag to check whether record found or not
        int foundRecord = 0;
        printf("Enter name to search : ");
        // fgets gets name to search
        fgets(search, 50, stdin);
        //remove the '\n' at the end of string
        search[strcspn(search, "\n")] = 0;

        
        while (fgets(record, 50, fPtr))
        {
            // strstr returns start address of substring in case if present
            if (strstr(record, search))
            {
                token = strtok(record, s); 

                while (strtok != NULL)
                {

                    scanf("%s", c.name);
                    token = strtok(record, s);
                    scanf("%d", c.age);
                    token = strtok(record, s);
                    scanf("%d", c.phoneNo);
                    token = strtok(NULL, s);

                    printf("Your details: ");
                    printf("%s, %d, %d\n", c.name, c.age, c.phoneNo);

                }
                
                foundRecord = 1;
            }
        }
        if (!foundRecord)
            printf("%s cannot be found\n", search);

        fclose(fPtr);
    }
    else
    {
        printf("File cannot be opened\n");
    }
}

我以前从未使用过 strtok,我不确定如何将每个标记存储到每个结构变量中。有人可以向我解释如何修复代码中的 strtok 函数吗?

如评论中所建议,您可以使用 strtok. You can use atoi/sscanf 轻松读取逗号分隔的字符串以从年龄中提取整数值。我稍微修改了您的代码以从文件中读取以分配给结构数组:

// Array for storing Profiles
struct profile profiles[2];

FILE* fPtr;
if (fPtr = fopen("profile.txt", "r")) {
    int index = 0;
    while (fgets(record, 50, fPtr) != NULL) {
        // Extract name
        char *pStr = strtok(record, ",");
        if (pStr != NULL) {
            strcpy(profiles[index].name, pStr);
        }
        // Extract Age
        pStr = strtok(NULL, ",");
        if (pStr != NULL) {
            profiles[index].age = atoi(pStr);
        }
        // Extract Phone No
        pStr = strtok(NULL, ",");
        if (pStr != NULL) {
            profiles[index].phoneNo = atoi(pStr);
        }
        index++;
    }

    for (int i = 0; i < 2; i++) {
        printf("%s %d %d\n", profiles[i].name, profiles[i].age, profiles[i].phoneNo);
    }
     
    fclose(fPtr);
}

当我 运行 这样做时,我能够看到预期的输出:

src : $ cat profile.txt 
James Brown,35y,0123456789
Mary Brown,45y,0123987456
src : $ gcc readfiletostructarr.c 
src : $ ./a.out 
James Brown 35 123456789
Mary Brown 45 123987456