首页 > 解决方案 > 将字符串的特定部分转换为整数

问题描述

*更新了我如何将字符串存储到我的结构中

我有一个结构如下:

struct patient {
    char name[30], ID[8];
    int age, phoneNo;
};

我写了以下代码:


int searchName()
{
    char search[30];
    char record[60];
    const char s[2] = ",";
    struct patient c;
    char a[8];
    int IDno;

FILE* fPtr;
    fPtr = fopen("patient.txt", "r");

    printf("Enter name to search : ");
    getchar();
    fgets(search, 30, stdin);

    //remove the '\n' at the end of string
    search[strcspn(search, "\n")] = 0;

    while (fgets(record, 60, fPtr))
    {
        // strstr returns start address of substring in case if present
        if (strstr(record, search))
        {
            char* pStr = strtok(record, ",");
            if (pStr != NULL) {
                strcpy(c.ID, pStr);
            }
            pStr = strtok(NULL, ",");
            if (pStr != NULL) {
                strcpy(c.name, pStr);
            }
            pStr = strtok(NULL, ",");
            if (pStr != NULL) {
                c.age = atoi(pStr);
            }
            pStr = strtok(NULL, ",");
            if (pStr != NULL) {
                c.phoneNo = atoi(pStr);
            }
        }

    }

    printf("%s", c.ID);
    strcpy(a, c.ID);
    printf("\n%s", a);
    IDno = atoi(a);
    printf("\n%d", IDno);
    return 0;
}

该代码允许我在文件中搜索字符串,使用 将字符串分成较小的字符串strtok,然后将它们存储到结构中。假设我在结构中存储了一个字符串“PT3” c.ID。在我的程序中,我试图将“PT3”字符串从 复制c.IDa,然后使用转换a为整数。我对此不太确定,但我认为通过将“PT3”转换为整数,只有整数“3”会保留在 中,这正是我想要的。IDnoatoiatoiIDno

编辑:问题似乎是我无法使用atoi. 将不胜感激从“PT3”中获取数字“3”以存储到IDno.

标签: cstringstructstrcpyatoi

解决方案


根据您的问题描述,看起来您需要sscanf(). 就像是

sscanf(a, "PT%d", &IDno);

应该做的工作。不要忘记进行错误检查。


推荐阅读