The reason why your program is not working is that the getchar gets all characters from input, including the enter key. When you type a number followed by the enter key the second getchar will read the enter (= '\n') and stop the program. It's better to use the gets function to read a complete line:
Actually, getchar only reads one character from the input stream. The first call to getchar reads properly but the second reads the newline or further characters that were left in the stream by the first call. This still has an unwanted effect similar to what you stated. And it's not better to use gets, period. gets is very unsafe and should be avoided like the plague, use fgets instead.
I found a few problems with this code, not the least of which was that the number converted can only be single digit since getchar only reads one digit of a larger number. I changed this as well as fixed the newline problem. The output was also incorrect since you were printing characters and not integers, with everything fixed and the program working properly I ended up with this:
Code:
#include <stdio.h>
int main ( void )
{
int answer, number;
answer = 'y';
do{
printf("\nEnter in the number you wish converted to hexadecimal: ");
scanf ( "%d%*c", &number );
printf("\nThe hexadecimal representation of %d is 0x%00X.", number, number);
printf("\nDo you wish to enter in a new number? (y/n): ");
answer = getchar();
}
while (answer == 'y');
return 0;
}
-Prelude