Home > Software design >  Why does it skip my command in C ? please check it
Why does it skip my command in C ? please check it

Time:11-19

#include <stdio.h>

int main()
{
  int inpa, med, oper, day, total;
  char agree;
  

  printf("                     Bach Mai Hospital");
  printf("\n\nHello, please enter your fee and we will calculate\npayment based on your insurance\n");
  printf("How many days have you been in the hospital ");
  scanf("%d", &day);
  printf("How much is your medicine fee ");
  scanf("%d", &med);

  printf("Have you undergone surgery (Yes or No)");
  scanf("%s", &agree);
  switch(agree){
  case 'Y':
    printf("Enter your surgery fee ");
    scanf(" %d", &oper);
    break;
  case 'N':
    oper = 0;
  break;
  };
  printf("%s", agree);

  inpa = day * 15000;
  printf("Your total fee\n");
  printf("Inpatient fee: %-10d x 15000 = %d\n", day, inpa);
  printf("Medicine fee: %-10d\n", med);
  printf("Surgery fee: %-10d\n", oper);
  total = inpa   med   oper;
  printf("\n\nYou pay: %d\n", total);

  return 0;

}
  

It skips my command from when I enter &oper

printf("Enter your surgery fee ");
    scanf(" %d", &oper);

And it is the result

  Bach Mai Hospital

Hello, please enter your fee and we will calculate
payment based on your insurance
How many days have you been in the hospital 8
How much is your medicine fee 90000000
Have you undergone surgery (Yes or No)Yes
Enter your surgery fee 80000000
PS D:\Desktop\Cprogram> 

I would be so thankful if someone explain for me why

previously I have trouble with the "agree" variable which I declare a char but it understands "agree" as int. Thank you

CodePudding user response:

printf("%s") expects a null character(\0). Whenever you want to print a character, you should use %c rather than %s.So replace printf("%s", agree); with print("%c",agree);, then everything works well.

CodePudding user response:

    printf("%s", agree);

This line seems to cause issue because:

  • agree is a char variable in stack and hold only 1 byte
  • When printf with %s, it is expected that you provide an char array end with value 0 which is string terminator.

Because of this when you call printf("%s", agree);, it will trigger a call to a string at address 'Y' or in hex value 0x59. And the access to this address is illegal and will cause undefined behavior for your program.

  •  Tags:  
  • c
  • Related