In check_letter and check_hour, you need to declare ch to be an int, since that's what getchar returns (that's how it can handle special return values like EOF).
Here's what's going on with the double enter deal:
- You ask the user for a single char with scanf. The input buffer is currently empty.
- The user presses <enter>, which sends that line of input to your program for consumption. There is nothing in the input buffer except the <enter> key, which corresponds to the '\n' (newline) character, so that char is read in and stored in your input variable. The input buffer is now empty again.
- Since input is neither an 'A' or a 'P', you enter the body of the while loop.
- You keep calling getchar in a loop until it receives a new line. But your input buffer is empty, so there is nothing for getchar to read. You need to type something to satisfy getchar (but remember, you need an <enter> to send the input to your program).
- You press <enter> again.
- Your getchar loop is satisfied and you can know print out the prompt "Enter correct letter: "
To fix this, only run your getchar loop if input is not a newline:
Code:
char input;
int ch; // must be int since getchar returns an int
while (scanf("%c", &input) != 1 || (input != 'A' && input != 'P'))
{
if (input != '\n') // only consume leftover input if there is leftover input
{
while ((ch = getchar()) != '\n')
;
}
printf("Enter correct letter: ");
}
So you have to think about what you expect of your user. You can have something like:
Code:
Enter an hour followed by A or P for AM/PM: 12A<enter>
or
Code:
Enter an hour: 12<enter>
Enter A for AM or P for PM: A<enter>
If you want the first type, you can wrap the two functions in one and use a slightly more complicate scanf: scanf("%d%c", ...). If you want the second, which I think you do, you will have to deal with the possibility that you may have several "Enter correct letter" statements on the screen if you have a dumb user. The only alternative is to use some sort of console manipulation library (e.g. ncurses) that lets you do fancy stuff like rewrite the same line. But those are complicated and too much effort for your project I think.