如何在C ++中将格式化的字符串HH:MM:SS转换为秒 [英] How to convert formatted string HH:MM:SS to seconds in C++
问题描述
我想将以HH:MM:SS格式格式化的字符串时间戳记仅转换为秒,然后将其与数字进行比较。我已经用Java编写了我的代码的主要版本,但是我单独向Scanner询问,而不是花费 string
时间。我对Java ++不太熟悉。想知道如何用C ++做到吗?
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++?
简单点说, String s = 1:01:01;
和字符串s2 = 3600;
我需要知道 if(s> s2)
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);
}
}
推荐答案
我将冒风险投票并提醒您,我们的工具箱中仍然有 sscanf
。
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;
}
这篇关于如何在C ++中将格式化的字符串HH:MM:SS转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!