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

Time:05-31

I wanted to exit the while loop after user input something besides 1. But it always end only after printing Enter book code:.

Here is the 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;
}

CodePudding user response:

You need to use either &bookCode[0] or, simply, bookCode as the parameter to the scanf call.

C arrays "decay" to a pointer, see here for a full explanation: https://stackoverflow.com/a/38857777/1607937

Also see https://stackoverflow.com/a/5407121/1607937

  • Related