时间转换(scanf的指定格式读入)

给定一个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;
}

  

转载于:https://www.cnblogs.com/cstdio1/p/11140991.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值