Thread: Trouble with Tokens

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    54

    Trouble with Tokens

    *Edited*

    Sorry, I found the source of the problem..
    Last edited by DarrenY; 05-21-2005 at 06:38 AM. Reason: Problem Solved

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    It's ok to post solutions to your own post. It may help others and others may find additional problems or suggest additional solutions.

    gg

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    54
    My humble apologies for removing the codes, Codeplug, I'll take note on that in the future.

    Ok, its like this, my initial problem was when I input my date (i.e. 13/2/2005). My expected output was (1322005). However, it came out to be '0000' instead. Here's my piece of code:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(){
    
     char dateInput[16], *p;
     char *tokenPtr;
     int StartDay=0;
     int StartMonth=0;
     int StartYear=0;
     int numFieldStartDate = 0;
     const char delit[] = "/";
     int startDateCounter = 0;
    
    
     printf("Enter Start Date: ");
     fgets(dateInput, sizeof(dateInput), stdin);
     if((p=strchr(dateInput, '\n'))!=NULL)
         *p = '\0';
    
    /*Token input*/
     tokenPtr = strtok(dateInput,delit);
    
     while(tokenPtr!=NULL){
    
       startDateCounter++;
       numFieldStartDate++;
    
       switch(startDateCounter){
    	case '1' : StartDay = atoi(tokenPtr);
    		break;
    	case '2' : StartMonth = atoi(tokenPtr);
    		break;
    	case '3' : StartYear = atoi(tokenPtr);
    		break;
       }
    
       tokenPtr = strtok(NULL, delit);
    
     }
    /*if user inputs the wrong date format*/
       if(numFieldStartDate != 3){
    	printf("Invalid format");
    	exit(-1);
       }
    	
    /*Display Tokens*/	 
     printf("\n%d", StartDay);
     printf("%d", StartMonth);
     printf("%d\n", StartYear);
    
    	return 0;
    }
    Input : 13/2/2005
    Expected Output : 1322005
    Program Output : 0000

    The reason I convert them to integers so that I can compare my dates with other dates later in the program..

    So, here's my solution

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(){
    
     char dateInput[16], *p;
     char *tokenPtr;
     int StartDay=0;
     int StartMonth=0;
     int StartYear=0;
     int numFieldStartDate = 0;
     const char delit[] = "/";
     int startDateCounter = 0;
    
    
     printf("Enter Start Date: ");
     fgets(dateInput, sizeof(dateInput), stdin);
     if((p=strchr(dateInput, '\n'))!=NULL)
        *p = '\0';
    
    /*Token input*/
     tokenPtr = strtok(dateInput,delit);
    
     while(tokenPtr!=NULL){
    
       startDateCounter++;
       numFieldStartDate++;
    
    /* The problem was here and fixed, 
       I had my inverted commas removed*/
       switch(startDateCounter){
    	case 1 : StartDay = atoi(tokenPtr);
    		break;
    	case 2 : StartMonth = atoi(tokenPtr);
    		break;
    	case 3 : StartYear = atoi(tokenPtr);
    		break;
       }
    
       tokenPtr = strtok(NULL, delit);
    
     }
    /*if user inputs the wrong date format*/
       if(numFieldStartDate != 3){
    	printf("Invalid format");
    	exit(-1);
       }
    	
    /*Display Tokens*/	 
     printf("\n%d", StartDay);
     printf("%d", StartMonth);
     printf("%d\n", StartYear);
    
    	return 0;
    }
    Is there a better way in dealing with dates? I mean to compare them with other dates.
    Last edited by DarrenY; 05-21-2005 at 12:57 PM.

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >Is there a better way in dealing with dates?

    For formatted input in general you might want to consider sscanf.
    Code:
    #include <stdio.h>
    #include <time.h>
    
    int main(void)
    {
       char dateInput[16];
       fputs("Enter Start Date: ", stdout);
       fflush(stdout);
       if ( fgets(dateInput, sizeof(dateInput), stdin) )
       {
          struct tm start = {0};
          if ( sscanf(dateInput, "%d/%d/%d", 
                      &start.tm_mday, &start.tm_mon, &start.tm_year) == 3 )
          {
             printf("%d%d%d\n", start.tm_mday, start.tm_mon, start.tm_year);
          }
       }
       return 0;
    }
    
    /* my output
    Enter Start Date: 13/2/2005
    1322005
    */
    >I mean to compare them with other dates.

    You may want to look into difftime and others in time.h.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Walked away before hitting submit - but here's my post even though it's identical advice:

    You could use sscanf() to do a lot of the parsing work for you:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    /* scanf format specification field to skip date seperators '-' and '/' */
    #define SKIP_DATE_SEPS  "%*[-/]"
    
    /* format specification for extracting month, day, year as unsigned ints */
    #define EXTRACT_DATE_MDY    "%2u" SKIP_DATE_SEPS "%2u" SKIP_DATE_SEPS "%4u"
    
    #define VALID_MONTH(m)  (((m) >= 1) && ((m) <= 12))
    #define VALID_DAY(d)    (((d) >= 1) && ((d) <= 31))
    #define VALID_YEAR(y)   ((y) >= 2005)
    
    int main()
    {
        char dateInput[16];
        unsigned int month, day, year, converted;
    
        printf("Enter Start Date: ");
    
        if (!fgets(dateInput, sizeof(dateInput), stdin))
        {
            fputs("Error getting input", stderr);
            return 1;
        }
    
        converted = sscanf(dateInput, EXTRACT_DATE_MDY, &month, &day, &year);
    
        if (converted != 3)
        {
            fputs("Invalid input\n", stderr);
            return 2;
        }
        else if (!VALID_MONTH(month))
        {
            fputs("Invalid month\n", stderr);
            return 3;
        }
        else if (!VALID_DAY(day))
        {
            fputs("Invalid day\n", stderr);
            return 4;
        }
        else if (!VALID_YEAR(year))
        {
            fputs("Invalid year\n", stderr);
            return 5;
        }
        
        printf("[%u-%u-%u]\n", month, day, year);
        
        return 0;
    }
    I'm no C-input guru, so this can probably be improved. As for comparing dates, just compare the year first, then month, then day.
    If you have to deal with hours, minutes, and seconds as well - then using struct tm with the time functions provided by <time.h> may be more appropriate.

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 01-03-2007, 03:02 PM
  2. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  3. Splitting A String Into Tokens!
    By bobthebullet990 in forum C Programming
    Replies: 15
    Last Post: 03-22-2006, 09:24 AM
  4. trouble scanning in... and link listing
    By panfilero in forum C Programming
    Replies: 14
    Last Post: 11-21-2005, 12:58 PM
  5. How to output tokens in reverse order using strtok
    By Ninz in forum C++ Programming
    Replies: 4
    Last Post: 02-01-2003, 09:00 PM