In the follow code, I want to just use one printf at the end of the program to print the 12-hour time, but I want it to print am or pm depending on which is stored in the variable am_pm.
I thought I read that I could store characters in int (or floats?), though I’m not sure if I remember correctly. Of course, it seems illegal since I’m getting type errors.
I also read that I can use arrays to do this, but I haven’t learned about arrays yet and I was wondering if there was a simpler substitute for such a problem.
I know the alternative is to simply use two printf‘s, one where I simply type “am” and one where I simply type “pm” at the end of the string, but that seems redundant to me.
#include <stdio.h>
int main(void) {
int hour, minutes, am_pm;
printf("Enter a 24-hour time:"); scanf("%d:%d", &hour, &minutes);
if (hour > 12)
{
hour = (hour - 12);
am_pm = "pm"; // ERROR
}
else
am_pm = "am"; // ERROR
printf("Equivalent 12-hour time: %.2d:%.2d%d", hour, minutes, am_pm);
} // end main
How can I do something similar to what I’m trying to do above? I know in python I would simply do something such as print(“equivalent time is:” + hour + minutes + am_pm)
First of all am_pm is declared as int and a few lines below you try to assign string to it. This is illegal. The other answers show how to correct this. I’d add another solution:
If this seems strange to you – read about ‘question mark operator’.