Reputation: 21
Input is in the format: hh:mm:ssAM or hh:mm:ssPM
Example:
INPUT: 07:05:45PM
OUTPUT: 19:05:45
#include <bits/stdc++.h>
#include<iostream>
#include<string>
using namespace std;
int main()
{
int hh,mm,ss ;
char tz[2];
cin>>hh>>mm>>ss>>tz;
if(strcmp(tz,"AM")==0 && hh==12)
{
hh=0;
}
else if(strcmp(tz,"PM")==0 && hh!=12)
{
hh += 12;
}
cout<<hh<<":"<<mm<<":"<<ss;
return 0;
}
Unlike the expected output i.e 19:05:45 I am getting 7:0:0
Upvotes: 0
Views: 2012
Reputation:
If your format is fixed, what about modifying the string in-place ?
if (time[8] == 'P') {
if (time[1] < '8') {
time[1]+= 2; time[0]+= 1; // No carry
}
else {
time[1]-= 8; time[0]+= 2; // Carry
}
}
(This assumes the ANSI collating sequence. It is million times more efficient.)
Upvotes: 0
Reputation: 87959
Your statement cin>>hh>>mm>>ss>>tz;
takes no account of the colons in your input. It's an example of how code that's roughly right is actually no good at all. You have to get code exactly right. You can't just write something that is roughly right and hope that the computer will understand what you mean.
You also have an error in the way you declared tz
. Remember that for a C style string you have to have room for the nul terminator. So you need an array one bigger that the maximum length of your string, i.e. char tz[3];
.
Another problem is the headers. The correct header for strcmp
is #include <cstring>
(the <string>
header is for C++ strings which you aren't using) and <bits/stdc++.h>
is not a standard C++ header, you should get out of the habit of using that.
Here's how I might do this
int hh, mm, ss;
char dummy1, dummy2, tz[3];
cin >> hh >> dummy1 >> mm >> dummy2 >> ss >> tz;
The purpose of the dummy variables is to read the colons. You aren't interested in the colons but you can't just ignore them.
This code has no checking for errors in the input, which in a real-world program would be a serious problem. But maybe for a tutorial program that doesn't matter.
Upvotes: 1
Reputation: 2290
Here look your input carefully .
INPUT 07:00:05PM,
Here after hour,minute ,there is an colon but you are not considering it during input. So please take an colon as input after hour and minute.
For example:
char tz[3],colon;
cin>>hh>>colon>>mm>>colon>>ss>>tz;
Full code will be:
#include <bits/stdc++.h>
#include<iostream>
#include<string>
using namespace std;
int main()
{
int hh,mm,ss ;
char tz[3],colon;
cin>>hh>>colon>>mm>>colon>>ss>>tz;
if(strcmp(tz,"AM")==0 && hh==12)
{
hh=0;
}
else if(strcmp(tz,"PM")==0 && hh!=12)
{
hh += 12;
}
cout<<hh<<":"<<mm<<":"<<ss;
return 0;
}
Upvotes: 0