码迷,mamicode.com
首页 > 其他好文 > 详细

时间转换

时间:2019-07-05 22:33:50      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:sub   成员函数   cst   时间   string类   math   输入   str   转换   

给定一个12小时制的时间,请将其转换成24小时制的时间。说明:12小时制的午夜12:00:00AM,对应的24小时制时间为00:00:00。12小时制的中午12:00:00PM,对应的24小时制时间为12:00:00。

输入描述:

一个描述12小时制时间的字符串。所有的输入都是合理的,不用考虑输入不合理的情况。

输出描述:

一个描述24小时制时间的字符串。

解题:利用string类的substr和stoi成员函数

#include <iostream>
#include <cmath>
#include <algorithm>
#include <set>
#include <cstdio>
#include <string>
#include <cstring>

using namespace std;
 

int main()
{
	string str;
	cin>>str;

	if(str.substr(8,2)=="AM")
	{
		if(str.substr(0,2)=="12"){
			str[0]=‘0‘;str[1]=‘0‘;
		}
			cout<<str.substr(0,str.size()-2)<<endl;	
	} 
	else{
		if(str.substr(0,2)!="12"){
		int t=stoi(str.substr(0,2))+12;
		str[0]=t/10+‘0‘;
		str[1]=t%10+‘0‘;
		}		
		cout<<str.substr(0,str.size()-2)<<endl;
	}
	
 
 
 
    return 0;
}
 

  利用scanf指定格式读入

#include<stdio.h>
#include<string.h>
 
int main() {
    int a, b, c;
    char str[5];
 
    scanf("%d:%d:%d%s", &a, &b, &c, str);
    str[2] = 0;
    if (strcmp(str, "PM") == 0) {
        if (a != 12) a += 12;
        printf("%02d:%02d:%02d", a, b, c);
    }
    else {
        if (a == 12) a=0;
        printf("%02d:%02d:%02d", a, b, c);
    }
    return 0;
}

  

时间转换

标签:sub   成员函数   cst   时间   string类   math   输入   str   转换   

原文地址:https://www.cnblogs.com/cstdio1/p/11140991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!