Can somebody help me ? My output is not working.

Write a program that inputs a time from the console. The time should be in
the format "HH:MM AM" or "HH:MM PM". Hours may be one or two digits, for
example, "1:10 AM" or "11:30 PM". Your program should include a function
that takes a string parameter containing the time. This function should
convert the time into a four-digit military time based on a 24-hour clock.
For example, "1:10 AM" would output "0110 hours", "11:30 PM" would
output "2330 hours", and "12:15 AM" would output "0015 hours". The
function may either write the time to the console or return a string to be
written to the console by the main function.

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

string convertToMilitaryTime(string time)
{
//gets colon and space position in the
// given time string
int colon = time.find(':');
int space = time.find(' ');

//extracts hours, minutes and meredian strings from the
// input time string
string hh = time.substr(0, colon);
string mm = time.substr(colon+1, space-colon-1);
string mer = time.substr(space+1);

//converts hours from string format to integer
int hours = atoi(hh.c_str());

// updating hours based on meredian
if(mer == "PM" &&hours != 12)
hours = hours + 12;
else if ( mer == "AM" &&hours == 12)
hours = 0;

//placing leading zero in hours if hour is one digit
if( hours >= 0 &&hours <= 9)
hh = "0";
else
hh = "";

//converring modified hours to string format
char H[5];
hh += itoa(hours,H,10) ;

//returns required output string
return hh + mm + " hours";
}

// main function
int main()
{
// inputs time in the form hh:mm AM/PM
string time;
cout << "Enter time (HH:MM AM) or (HH:MM PM): ";
getline(cin,time,'n');

//calls convertToMilitaryTime to conevert the given
//time into military time

string milTime = convertToMilitaryTime(time);

//displays to the console
cout << milTime << endl;
return 0;
}
Last edited on
Did you mean for that last parameter to be a newline '\n' ?

getline(cin,time,'n');


Edit: The itoa function is apparently non-standard. (http://www.cplusplus.com/reference/cstdlib/itoa/) I couldn't get the code to compile on the built-in compiler here (www.cpp.sh)
Last edited on
Line 48: You're telling getline to read until it finds a 'n'. You want to read until a newline ('\n').

 
  getline (cin,time,'\n');


PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
THANK VERY MUCH GUYS!!!!!!!!!!!!!!!!!!!!!!!!1
Topic archived. No new replies allowed.