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';
}
}
CodePudding user response:
line[j] = line[j 1];
above line may be the reason behind segmentation fault. (although your code is working fine in c )
CodePudding user response:
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);