My apologies algorism I did not pick up on what you meant by that.
[ QUOTE=algorism;1264924]Hello??!! That's the entire point of my post!!![/QUOTE]
Again, it's a matter of the relative position of the code. Instead of testing if hr is 1 (which it will be over and over again from 1:00 to 1:59), put the am/pm code in where hr is set to 1.
EDIT: Actually, now that I think about it that's not quite right. It's more like:Code:if (++min > 59) { min = 0; if (++hr > 12) { hr = 1; // put the am/pm code in here (but don't bother checking for hr == 1 since we already know that) } }
Code:if (++min > 59) { min = 0; if (++hr == 12) { // put the am/pm code in here } else if (hr > 12) hr = 1; }
Last edited by algorism; 01-26-2017 at 04:00 PM.
I added what you suggested previously and my only remaining problem was the AM not switching to PM
But now not even the minutes are incrementing properly
Any idea where I went wrong?
Code:for(i=0;i<addtime;i++) { if (++min > 59) { min = 0; } if (++hr == 12 && ampm=='P') { ampm='A'; } if (++hr == 12 && ampm=='A') { ampm='P'; } else if(hr>12) { hr=1; } printf("%d:%.02d %cM\n",hr,min,ampm);
That is a bit of a mess. It's important to indent things properly so you can see what's going on. I believe the following is correct. Note that it's a matter of putting things in the right place so they are controlled by the right conditions.
Code:for (i = 0; i < addtime; i++) { if (++min > 59) { min = 0; if (++hr == 12) { if (ampm == 'A') ampm = 'P'; else ampm = 'A'; } else if (hr > 12) hr = 1; } printf("%d:%.02d %cM\n", hr, min, ampm); }
Much better. Thanks for your help!
One last problem....
How do I validate that input is numeric? If I enter a for minutes the program will just start a never ending loop.
Check the return value of scanf() - it returns the number of successful conversions. If invalid data is entered (e.g. zero conversions were performed), the offending input remains on the input buffer and needs to be cleared. See here for suggestions on how to clear the input buffer in this situation: FAQ > Flush the input buffer - Cprogramming.com
A better solution would be to read an entire line using fgets(), and extract the data from the string using sscanf(). This will eliminate the need to clear the input buffer if bad input is entered.