Advertisement
spikeysnack

scanf time demo

Sep 3rd, 2020
1,385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <stdio.h>   /* fscanf, fprintf */
  2. #include <errno.h>   /* errno           */
  3. #include <string.h>  /* strerror        */
  4. #include <stdbool.h>
  5.  
  6. typedef struct
  7. {
  8.   unsigned h;
  9.   unsigned m;
  10.   unsigned s;
  11. } HMS;
  12.  
  13. /* format time */
  14. bool convert(HMS* hms)
  15. {
  16.   bool over24 = false;
  17.  
  18.   if (hms->s >= 60) { hms->m++;  hms->s%=60; }
  19.  
  20.   if (hms->m >= 60) { hms->h++;  hms->m%=60; }
  21.  
  22.   if (hms->h >= 24) { hms->h%=24; over24=true;   }
  23.  
  24.   return over24;
  25. }
  26.  
  27. int main(int argc, char** argv)
  28. {
  29.   HMS t;
  30.   int n = 0;
  31.   errno = 0;
  32.  
  33.   if (argc> 1)
  34.     {
  35.       n = sscanf( argv[1] , "%2u:%2u:%2u", &t.h, &t.m, &t.s);
  36.     }
  37.   else
  38.     {
  39.       fprintf(stdout, "Enter the time (hh::mm:ss):\t" );
  40.  
  41.       n = fscanf( stdin, "%2u:%2u:%2u", &t.h, &t.m, &t.s);
  42.     }
  43.  
  44.  
  45.   if( n==3  &&  !errno)
  46.     {
  47.       if ( convert(&t) ) fprintf( stdout, "clock turned over (>24 hrs)\n\n");
  48.        
  49.       fprintf( stdout, "hours:    %d \n" , t.h);
  50.      
  51.       fprintf( stdout, "minutes:  %d \n" , t.m);
  52.      
  53.       fprintf( stdout, "seconds:  %d \n" , t.s);
  54.     }
  55.   else
  56.     fprintf(stdout, "invalid format. %s\n", strerror(errno) );
  57.  
  58.   return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement