Created
August 17, 2010 13:05
-
-
Save Soft/529841 to your computer and use it in GitHub Desktop.
Time to seconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
// 1h 26m 15s -> 5175 | |
unsigned int time_to_seconds(const char *str) { | |
const char *current = str; | |
unsigned int seconds = 0, number = 0; | |
while (*current) { | |
switch (*current) { | |
case 'h': | |
seconds += number * 60 * 60; | |
number = 0; | |
break; | |
case 'm': | |
seconds += number * 60; | |
number = 0; | |
break; | |
case 's': | |
seconds += number; | |
number = 0; | |
break; | |
case ' ': | |
break; | |
default: | |
if (*current >= 48 && *current <= 57) { // 0-9 | |
number = number * 10 + (*current - 48); | |
} else { | |
int index = (int)(current - str); | |
printf("Invalid character '%c' at %d\n", *current, index); | |
exit(EXIT_FAILURE); | |
} | |
break; | |
} | |
++current; | |
} | |
return seconds; | |
} | |
main(int argc, char *args[]) { | |
if (argc > 1) { | |
unsigned int seconds = time_to_seconds(args[1]); | |
printf("%s is %d seconds\n", args[1], seconds); | |
exit(EXIT_SUCCESS); | |
} else { | |
printf("No input\n"); | |
exit(EXIT_FAILURE); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment