标签:sub 成员函数 cst 时间 string类 math 输入 str 转换
一个描述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