如何在C++中将格式化字符串HH:MM:SS转换为秒

Tin*_*a J 4 c++ datetime

我想将以HH:MM:SS格式化的字符串时间戳转换为仅秒,然后将其与数字进行比较.我用Java编写了我的代码的主要版本,但是我分别向Scanner询问,而不是有string时间.我对C++库不是很熟悉,因为我是一个Java人.想知道我怎么能用C++做到这一点?

尽量简短,String s = "1:01:01";而且String s2= "3600";我需要知道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);

    }
}
Run Code Online (Sandbox Code Playgroud)

Rod*_*ddy 8

我将冒险投票并提醒您我们仍然sscanf在我们的工具箱中.

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;
}
Run Code Online (Sandbox Code Playgroud)