Search code examples
cstringstructstrcpyatoi

converting specific part of string to integer


*updated with how i stored the string into my struct

I have a struct as below:

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

and i've written the following code:


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;
}

the code allows me to search for a string in a file, separate the string into smaller strings using strtok, then store them into the struct. suppose i stored a string "PT3" into c.ID in the struct. in my program, I am trying to copy the string of "PT3" from c.ID to a, then convert a to an integer IDno using atoi. I'm not too sure about this, but I think by using atoi to convert "PT3" to an integer, only the integer "3" will remain in IDno, which is exactly when I want.

edit: the problem appears to be that i am unable to convert "PT3" to an integer using atoi. would appreciate help on getting the number "3" from "PT3" to be stored into IDno.


Solution

  • As per your problem description, looks like you need sscanf(). Something like

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

    should do the job. Don't forget to do the error check.