fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. int string2sec(const std::string& str) {
  6. int i = 0;
  7. int res = -1;
  8. int tmp = 0;
  9. int state = 0;
  10.  
  11. while(str[i] != '\0') {
  12. // If we got a digit
  13. if(str[i] >= '0' && str[i] <= '9') {
  14. tmp = tmp * 10 + str[i] - '0'; // Little bug fix here
  15. }
  16. // Or if we got a colon
  17. else if(str[i] == ':') {
  18. // If we were reading the hours
  19. if(state == 0) {
  20. res = 3600 * tmp;
  21. }
  22. // Or if we were reading the minutes
  23. else if(state == 1) {
  24. res += 60 * tmp;
  25. }
  26. // Or if we were reading the seconds
  27. else if(state == 2) {
  28. res += tmp;
  29. }
  30. // Or we got an extra colon
  31. else {
  32. return -1;
  33. }
  34.  
  35. state++;
  36. tmp = 0;
  37. }
  38. // Or we got something wrong
  39. else {
  40. return -1;
  41. }
  42. i++;
  43. }
  44.  
  45. return res;
  46. }
  47. int main() {
  48. std::cout << string2sec("1:01:01") << std::endl;
  49. return 0;
  50. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
3660