Home > Software engineering >  Bizzare bug in date conversion program
Bizzare bug in date conversion program

Time:10-07

I can't fix a weird bug i have in my code.

I wrote a program to print a date originally written in format "MM/DD/YYYY" to format "Month DD, YYYY".

The program is simple enough: i store the date in a char array, then with strtok i obtain month, day, year individually and store pointers to them in a char * array. Eventually the portion of the string representing the month is converted to int , so as to use it as an index to print the month; day and year are printed separately.

The program works, but i really can't wrap my head around the fact that it doesn't if i input 08 (August) or 09 (September) as month.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    void read_date( char * const);
    void collect_data( char * const, char *[] );
    int convert_month( char * );

    int main() {

         char *months[12] = {"January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December" };
         char orig_date[11];
         char *date_elem[3];

         int month;

         read_date( orig_date );

         collect_data( orig_date, date_elem );

         month = convert_month( date_elem[0] );

         puts("\n*New format*\n");
         printf( "%s %s, %s\n", months[month - 1], date_elem[1], date_elem[2]);

    }

    void read_date( char * const date ) {

         int i = 0;
         char c;

         puts("Enter date in format MM/DD/YYYY:\n");

         while ( i < 11 && ( c = getchar() ) != '\n' ) {

              date[i  ] = c;
         }

         date[i] = '\0';
     }

     void collect_data( char * const date, char *elem[] ) {

          char *ptr;
          int i = 0;

          ptr = strtok( date, "/" );

          while ( ptr != NULL ) {

               elem[i  ] = ptr;
               ptr = strtok( NULL, "/" );
          }

      }

      int convert_month( char *m ) {

           char *rem;

           return strtol( m, &rem, 0);

      }

CodePudding user response:

You use base 0 for parsing integers from the month part:

return strtol( m, &rem, 0);

That means it will auto-detect the numeric base, which assumes base-8 (octal) representation for zero-prefixed input numbers. You might want to hard-code usage of base 10 there.

The numbers 08 and 09 do not exist with octal number representation. You receive 0 there, as it stops parsing at the first invalid character it encounters. See below link for how you could improve your error handling with strtol().

For reference:

  • Related