In: Computer Science
I have the below program and I am having issues putting all the output in one line instead of two.
how can I transform the program for the user enter
format ( HH:MM)
Like:
Enter time using 24 format ( HH:MM) : " and the user enter format "
14:25
then the program convert. instead of doing two lines make all one
line.
Currently I have the user enter first the Hour and then the minutes but i'd like to change the program to have the user enter the Hour and Minute in the same line. using format : " HH:MM"
#include<iostream>
using namespace std;
void input(int& hours24, int& minutes){
cout<<"Enter hours [0 -23]: "; cin >>
hours24;
cout<<"Enter minutes [0 - 59]: "; cin >>
minutes;
}
void output(int hours, int minutes, char AMPM){
if(hours<10) cout<<"0"; cout<<hours;
cout<<":";
if(minutes<10) cout<<"0";
cout<<minutes;
if(AMPM=='A') cout<<" AM";
else cout<<" PM";
cout<<endl;
}
void convert(int& hours, char& AMPM){
if(hours>12){
hours-=12;
AMPM = 'P';
}
else if(hours==12){
AMPM ='P';
}
else if(hours==0){
hours += 12;
AMPM ='A';
}
else{
AMPM = 'A';
}
}
int main(){
int hours, minutes;
char AMPM, ans;
do{
input(hours,minutes);
if(hours<0 || hours>23 ||
minutes<0 || minutes>59){
cout<<"Error: Invalid hours/minutes entered.\n";
cout<<"Program will terminate.\n";
break;
}
convert(hours,AMPM);
output(hours,minutes,AMPM);
cout<<"Enter Y or y to
continue,"
<<"
anything else quits.\n";
cin >>
ans;
}while(ans=='Y' || ans =='y');
return 0;
}
Answer: Hey dear student finds the solution of your query, if you have any doubt feel free to ask. Thanks!!
Modified Code: Output in single line only , you can see snapshot of the output.
#include<iostream>
using namespace std;
//this function is modified only ,one parameter added to take character ':'
void input(int& hours24, int& minutes,char &ch)
{
cout<<"Enter a 24-hour time (ex. 15:23):
";
cin >> hours24>> ch
>>minutes;
//when we input 13:45 13
store in hours24,':' store in ch,45 store in
minutes
}
void output(int hours, int minutes, char AMPM){
if(hours<10) cout<<"0"; cout<<hours;
cout<<":";
if(minutes<10) cout<<"0"; cout<<minutes;
if(AMPM=='A') cout<<" AM";
else cout<<" PM";
cout<<endl;
}
void convert(int& hours, char& AMPM){
if(hours>12){
hours-=12;
AMPM = 'P';
}
else if(hours==12){
AMPM ='P';
}
else if(hours==0){
hours += 12;
AMPM ='A';
}
else{
AMPM = 'A';
}
}
int main(){
int hours, minutes;
char AMPM, ans,chr;
do{
input(hours,minutes,chr);
if(hours<0 || hours>23 || minutes<0 ||
minutes>59){
cout<<"Error: Invalid hours/minutes entered.\n";
cout<<"Program will terminate.\n";
break;
}
convert(hours,AMPM);
output(hours,minutes,AMPM);
cout<<"Enter Y or y to continue,"
<<" anything else quits.\n";
cin >> ans;
}while(ans=='Y' || ans =='y');
return 0;
}
Output: