This is the question:

Write a program that converts from 24hour notation to 12hour notation.For example, it should
convert 14:30 to 2:30 PM. The input is given as two integers. Verifies that a legitimate 24hour
notation has been input by using the assert statement

Please tell me if my code is correct

Here's my code:

#include <iostream>
#include <cassert>
using namespace std;

int main()
 {
int hours, mins;
string period;

cout << "Enter the hours you wish to convert(0 - 2)";
cin >> hours;
assert(hours >= 0 && hours <= 24);

cout << "Enter the minutes you wish to convert(0 - 59);
cin >> mins;
assert(mins >= 0 && mins <= 59);

if(hours > 12)
{
    hours = hours - 12;
    period = "PM";
 }
else
{
period = "AM";
 }

 cout << "The converted time in 12-hour notation is " << 
 hours << ":" << mins << period;
 return 0;
}

Please tell me if my code is correct

Compile your program for DEBUG and you can find out for yourself if it is correct or not. assert() does nothing if the program is compiled for release. How to do that will depend on the compiler you are using.

Edited 4 Years Ago by Ancient Dragon

Verifies that a legitimate 24hour notation has been input by using the assert statement

Just so you understand, this is an extremely poor practice. The assert() macro should only be used for shaking out bugs because it invokes a hard stop on the process. Here you're using it for validation of user input, which is almost guaranteed to be incorrect at least half the time for free form input.

Put a different way, do you really want to crash the program when the user fat fingers a number?

I thought that was a requirement imposed by the assignment.

Yes, that's correct. But since this forum is about learning and not simply regurgitating answers, I wanted to explain that the question is encouraging bad practices and why the practice is bad.

Edited 4 Years Ago by deceptikon

I have no choice, that's a question given in my assignment that's due tmrw.

I have no choice, that's a question given in my assignment that's due tmrw.

Oh my god, I know! Seriously, I read the question and understand that it specifies assert(). For future reference, it's bad practice. Keep that in mind, but answer the question appropriately, since it requires you to use the assert() macro. I fail to see how this is difficult to understand.

Edited 4 Years Ago by deceptikon

In other words running the program should not depend that asserts are actually enabled when it is run.

This article has been dead for over six months. Start a new discussion instead.