4位BCD到7段

问题描述 投票:0回答:1

我正在将4位BCD解码器制作为c中的7段显示器。显示输出后,请问用户是否要再次输入。我可以显示所需的输出,并且当我不想再次输入时可以退出程序。问题是当我想再次输入时,它不会停止询问我的输入并打印先前的输入。Screenshot

这是我的代码。

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);   
}
c
1个回答
0
投票

在给出输入1\n以继续下一个7段号之后,只有1scanf()捕获,\n留在后面。

但是格式[^\n]告诉scanf()拒绝以\n开头的任何inpunt,因此剩余部分将返回以下内容,而不会扫描任何值。检查其返回值,您会发现第二次为0,因此不会更新变量,这就是使用先前值的原因。

为了修复它,您只需从格式中删除[^\n],并进一步细化输入字符串。

© www.soinside.com 2019 - 2024. All rights reserved.