I want to convert a string time stamp formatted in HH:MM:SS to seconds only, and then compare it with a number. I have written a prime version of my code in Java, however I separately ask from Scanner as opposed to having a string
time. I'm not much familiar with C++ libraries, as I'm a Java guy. Wondering how I can do it in C++?
Make it brief, String s = "1:01:01";
and String s2= "3600";
I need to know if (s>s2)
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int hours;
int mins;
int secs;
System.out.println("Enter Hours: ");
hours = console.nextInt();
System.out.println("Enter Minutes: ");
mins = console.nextInt();
System.out.println("Enter Seconds: ");
secs = console.nextInt();
int showSecs = (hours * 3600) + (mins * 60) + secs;
System.out.println(hours + ":" + mins + ":" + secs + " in secs are "
+ showSecs);
}
}
I'll risk the downvotes and remind you that we still have sscanf
in our toolbox.
int h, m, s= 0;
std::string time ="10:40:03"
if (sscanf(time.c_str(), "%d:%d:%d", &h, &m, &s) >= 2)
{
int secs = h *3600 + m*60 + s;
}
As @ghostofstandardspast suggested you can use the std::get_time()
I/O manipulator to read a specific time format from a std::istream
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
#include <ctime>
int main() {
std::tm t;
std::istringstream ss("1:01:01");
ss >> std::get_time(&t, "%H:%M:%S");
std::cout << "Total seconds: "
<< t.tm_hour * 3600 + t.tm_min * 60 + t.tm_sec
<< std::endl;
}
Here's a fully working sample using clang. Unfortunately I couldn't get this sample running using GCC 4.8.x, I'd guess it's not complete in this implementation. May be GCC 4.9.x supports this correctly.
As looking for an alternative (if you can't use a compiler supporting the complete current c++11 standard actually), you may either consider to use std::sscanf()
as @Roddy suggested, or split the string using ':'
as delimiter character, and simply convert the split out parts to integer values, using the e.g. the atoi()
method.
Here's the alternative
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
std::vector<std::string> &split
( const std::string &s
, char delim
, std::vector<std::string> &elems)
{
std::istringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
int main() {
std::vector<std::string> parts;
split("1:01:01",':',parts);
if(parts.size() == 3) {
int hour = std::atoi(parts[0].c_str());
int min = std::atoi(parts[1].c_str());
int sec = std::atoi(parts[2].c_str());
std::cout << "Total seconds: "
<< hour * 3600 + min * 60 + sec
<< std::endl;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With