kush
kush

Reputation: 13

format the character from the array in structure

I have a structure in which there is a char line[20] = "2022/03/13 11:22:33". I have to format this char line as "20220313112233". I am trying like this but getting segmentation fault.

for (int i = 0, j; line[i] != '\0'; ++i) {
    while (! (line[i] >= '0' && line[i] <= '9') && ! (line[i] == '\0')) {
        for (j = i; line[j] != '\0'; ++j)
            line[j] = line[j + 1];
        line[j] = '\0';
    }
}

Upvotes: 1

Views: 37

Answers (2)

जलजनक
जलजनक

Reputation: 3071

Like it's pointed out in comments, use one loop to get the job done:

    #include <ctype.h> // for isdigit()
    char line[20] = "2022/03/13 11:22:33";
    for (char *ai = line, *zi = line; 1; ++zi) {
        if (isdigit (*zi))
            *ai++ = *zi;
        else if ('\0' == *zi) {
            *ai = '\0';
            break;
        }
    }
    printf ("\n%s\n", line);

Upvotes: 1

Yugal Kishore
Yugal Kishore

Reputation: 31

line[j] = line[j + 1];
above line may be the reason behind segmentation fault. (although your code is working fine in c++)

Upvotes: 0

Related Questions