I'm making a 4-bit BCD decoder to 7-segment display in C.
After the output is displayed I ask if the user wants to input again. I can display the desired output and I can exit the program when I don't want to input again.
The problem is when I want to input again it doesn't stop to ask for my input and prints the previous input.
This is the output:
This program displays the decimal equivalent of a
4-bit binary-coded decimal input on a 7-segment LED Display.
Please enter a 4-bit binary-coded decimal: 1000
You've entered 1000.
The decimal equivalent is 8.
_
|_|
LED Display: |_|
Would you like to input another 4-bit BCD?
Enter [1] if yes or [0] if no. 1
Please enter a 4-bit binary-coded decimal: You've entered 1000.
The decimal equivalent is 8.
_
|_|
LED Display: |_|
Would you like to input another 4-bit BCD?
Enter [1] if yes or [0] if no.
This is my code:
int main() {
int i, dec, retry = 1; //declare integers i ,dec, and retry
int bit[4]; //declare integer array with 4 elements
unsigned char input[5]; //declare string with 5 elements
printf("This program displays the decimal equivalent of a\n 4-bit binary-coded decimal input on a 7-segment LED Display.\n\n");
do {
printf("Please enter a 4-bit binary-coded decimal: "); //instructs user to enter 4-bit bcd
scanf("%[^\n]%*c", input); //read string
printf("You've entered %s.\n\n", input); //shows the 4-bit bcd input
for (i=0; i<5; i++) {
bit[i] = input[i] - '0';
}
dec = bit[0]*8 + bit[1]*4 +bit[2]*2 + bit[3];
printf("The decimal equivalent is %d.\n\n", dec); //shows decimal equivalent
switch (dec) { //displays 7-segment display depending on the value of dec
case 0:
printf(" _ \n | |\nLED Display: |_|\n");
break;
...
}
printf("\n\nWould you like to input another 4-bit BCD?\nEnter [1] if yes or [0] if no. ");
scanf("%d", &retry);
}
while (retry == 1);
}
I also encounter the same problem when using fgets(input, sizeof(input), stdin); instead of scanf("%[^\n]%*c", input);