-2

So I feel like I don't really understand the getchar() function very well... What I thought the code would do is, if there happens to be a space it will just "eat" that space with the getchar() function. And if there happens to not be a "p" in the input (as in 1:30 pm), then it will just keep "eating" the input until there is only '\n' left. And at that point it will end the while loop. But anyways, here's the code:

int main(void)
{
    int hour, min;
    char ch;

    printf("Enter a 12-hour time: ");
    scanf("%d : %d", &hour, &min);

    while ((ch = getchar()) != '\n')
    {
        if (toupper(ch) == 'P')
        {   hour += 12; }

    getchar();

    }

    printf("24-hour time: %d:%d", hour, min);
    return 0;
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • You've explained what your code is supposed to do, but what does it actually do? What problem are you experiencing with your current implementation? – ApproachingDarknessFish Feb 25 '15 at 07:14
  • You call `getchar()` twice in your loop, effectively skipping every other character and possibly missing the new-line character. Your (corrected, non-skipping) code would also parse `"12:00ppp"` as 48 o'clock. – M Oehm Feb 25 '15 at 07:21
  • Well the problem is that it's stuck in a loop. When i implement the code, it asks me for the time, and when i input a time and hit enter, it simply jumps to the next line of input. – krazibiosvn Feb 25 '15 at 07:22
  • @MOehm Thanks! that was the error >.> I don't know what i was thinking calling it twice... – krazibiosvn Feb 25 '15 at 07:24

2 Answers2

1

You have an extra call to getchar() in the while loop that is probably interfering with your logic. Remove it. You just need:

while ((ch = getchar()) != '\n')
{
   if (toupper(ch) == 'P')
   {
      hour += 12;
   }
}

To make it clean, change the type of ch from char to int since the return type of getchar() is int and check ch against EOF also.

int main(void)
{
   int hour, min;
   int ch;

   printf("Enter a 12-hour time: ");
   scanf("%d : %d", &hour, &min);

   while ((ch = getchar()) != '\n' && ch != EOF )
   {
      if (toupper(ch) == 'P')
      {
         hour += 12;
      }
   }

   printf("24-hour time: %d:%d", hour, min);
   return 0;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

getchar() is used to read a char from stdin. Here, you already read user input with scanf(). So your code could be:

#include <stdio.h>
#include <string.h>

int main(void)
{
    int hour, min;
    char ch;

    printf("Enter a 12-hour time: ");
    char fmt[3];
    scanf("%d : %d %s", &hour, &min, fmt);

    if (strcmp(fmt, "pm") == 0) {
       hour += 12;
    }
    printf("24-hour time: %d:%d", hour, min);
    return 0;
}
simurg
  • 1,208
  • 7
  • 14