"Enter book code" 即使用户输入的不是“1”,也始终打印

"Enter book code" always print even when user enter something besides "1"

我想在用户输入 1 以外的内容后退出 while 循环。但它总是在打印 Enter book code:.

后结束

代码如下:

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

int main(){
int cntinue, quantity, counter = 0;
char bookCode[50];
float bookPrice, totalPrice;

printf("Would you like to continue [Type 1 to continue] : ");
scanf("%d", &cntinue);

while(cntinue == 1){
    printf("Enter book code : ");
    scanf("%s", &bookCode);
    
        if(strcmp(bookCode, "B1001") == 0){
            bookPrice = 34.50;
            printf("Enter quantity : ");
                scanf("%d", &quantity);
            counter = counter + quantity;
            totalPrice = bookPrice * quantity;
            printf("Bill = RM %.2f\n", totalPrice);
            printf("Would you like to continue [Type 1 to 
 continue] : ");
                scanf("%d", &cntinue);
            
        }
        else if(strcmp(bookCode, "B1002") == 0){
            bookPrice = 77.30;
            printf("Enter quantity : ");
                scanf("%d", &quantity); 
            counter = counter + quantity;
            totalPrice = bookPrice * quantity;
            printf("Bill = RM %.2f\n", totalPrice);
            printf("Would you like to continue [Type 1 to 
 continue] : ");
                scanf("%d", &cntinue);
            
        }
        else if(strcmp(bookCode, "B1003") == 0){
            bookPrice = 54.90;
            printf("Enter quantity : ");
                scanf("%d", &quantity); 
            counter = counter + quantity;
            totalPrice = bookPrice * quantity;
            printf("Bill = RM %.2f\n", totalPrice); 
            printf("Would you like to continue [Type 1 to 
 continue] : ");
                scanf("%d", &cntinue);
        }
        else {
            break;
            printf("Your book code is invalid. Current purchase 
 cancelled.");
        }

}
        if(totalPrice != 0){
            printf("Total collection : RM %.2f", totalPrice);
        }

return 0;
}

您需要使用 &bookCode[0]bookCode 作为 scanf 调用的参数。

C 数组“衰减”为指针,完整解释请参见此处:

另见