cstringc-stringsstrcpystrchr

Trying to copy the remainder of a string after a character


I am trying to copy the remainder of a user inputted string. It is always input in the following: airport, 00:00, 00:00. The numbers are flight times and layover times. In my code I've gotten it to spit out the airport, but trying to use strchr to find everything after the 1st "," is a pain. Is there a way I can remove the airport and put the rest into a new string and continue to use strchr? I have to reformat the strings separated by commas is the goal. The end result should be “city has flight time tt.tt hoursand layover time tt.tt hours”. I cannot use scanf or the like so it looks like strchr and strcopy might be my only options. Any help is appreciated.

What I have currently gives me an error when trying to find the char after the last "," in the string.

Assignment Rules: Do not use strtok(), any scanf-related functions, any functions that do tokenization of string data.

int main()
{
    int counter = 0;
    int flightTimeNum = 0;
    char userInput[81] ="";
    char userInputNew[81] = "";
    char cityNew[20] = "";
    char flightTime[20] = "";
    char layOverTime[20] = "";


    fgets(userInput, 81, stdin);
    char *city;
    char *flight;
    char *layover;

    city = strchr(userInput, ',');
    strncpy(cityNew, userInput, city - userInput);
    printf("%s\n" ,cityNew);

    layover = strrchr(userInput, ',');
    strncpy(layOverTime, userInput, layover - userInput);
    printf("%s\n", layOverTime);

    printf("Press ENTER key to Continue\n");
    getchar();

}

Solution

  • If you want to use strchr you could consider creating substrings by replacing each ',' with a null terminator \0 and then setup the pointers to each sub string based on the length of the previous string.

    Alternatively, you could can through the string accumulating the characters until you reach a , and then terminate the buffer and start accumulating the next part of the string into the next buffer, and repeat until you reach the null terminator of the userInput.

    Example of the first approach, note you should validate that you were able to create the expected number of substrings etc. just in case the user enters invalid data.

    // NULL terminate each substring
    char *p = userInput;    // Point to the beginning of the string
    for(;;) {
        p = strchr(p, ','); // Find first ',' starting from 'p'
        if (!p) break;      // If not found break out of loop
        *p = '\0';          // otherwise replace ',' with a null terminator
        ++p;                // move pointer 'p' to the next character
    }
    
    // Setup pointers to each substring
    city = userInput; 
    flight = city + strlen(city) + 1;
    layover = flight + strlen(flight) + 1;