时间转换(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