0

I cant fix this gets, the next output will be productname:Price: Can someone help me how to fix it?

#include <stdio.h>

int main()
{    

    int price,quantity,total,cash,change,equal;
    char productname[50],c;
    
    do{
        
        printf("\n**** Welcome to my Store ****\n");
        printf("\nProduct Name:");
        gets(productname);
        
        printf("Price:");
        scanf("%d",&price);
        
        printf("Quantity:");
        scanf("%d",&quantity);
        
        switch(quantity)
        {
            case 1 :
            {
                printf("\nAdd another item? Press 'c' to continue | 'x' to calculate total amount to be paid:");
                scanf("%c",&c);
                scanf("%c");
                if(c!='c' && c!='x')
                   {
                     printf("\nInvalid Choice");
                     break;
                
                   }    
                break;
           } 
           case 2 :
           {
                printf("\nAdd another item? Press 'c' to continue | 'x' to calculate total amount to be paid:");
                scanf("%c",&c);
                scanf("%c");
                if(c!='c' && c!='x')
                   {
                     printf("\nInvalid Choice");
                     break;
                
                   }    
                break;
           }
            
              
        }   
    total = price * quantity;   

    }while(c!='x');
    
    printf("\n________________________________________________________________________");
    printf("\nTotal Amount:%d",total);
    printf("\nCash:");
    scanf("%d",&cash);
    change = cash - total;
    printf("Change:%d",change);
    
    return 0;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Newbie
  • 3
  • 2
  • 1
    You haven't really described the problem but I'm going to assume you aren't clearing the input stream after each input therefor your scanf is skipping the next input? – Irelia Dec 24 '21 at 15:06
  • 1
    Don't use `gets`: https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used – William Pursell Dec 24 '21 at 15:14
  • `scanf("%c");` is undefined behavior. If you want to consume one character and discard it, you can use `fgetc`. If you insist on using `scanf`, you could do `scanf("%*c")` or `scanf("%c", &c)`. You must have a valid argument to correspond to the conversion specifier or the behavior is undefined. – William Pursell Dec 24 '21 at 15:18
  • There's no default case in the switch, and the newline is still in the input buffer after the quantity is entered, so if `quantity` is not 1 or 2 the `gets(productname);` immediately returns after reading just that newline. – William Pursell Dec 24 '21 at 15:21

0 Answers0