-2

I have these two problems:

  1. I have this code which will take number of hours. If total_hours is greater than 60, then it should stop. It does stop, but then it shows the messageINPUT NOT VALID!! and asks for input again (which it should not.)
  2. Otherwise, is true the first input called "name" is not asked in the second time "when use put "Y" as an answer ".

Code:

#include <stdio.h>
#include <string.h>
int main() {
    int total_hours;
    char name[100], category[3], nic[140];
    float gross_pay, overtime_pay, net_pay;
    int straight_time = 44, pay_hour;
    char con;

    do {
        fgets(name, 100, stdin);

        printf("NIC:");
        fgets(nic, 140, stdin);

        printf("Category:");
        fgets(category, 3, stdin);

        printf("Total Hours:");
        scanf("%d", & total_hours);

        printf("\n\t\t  Smart Store Hypermarket \n");
        printf("============================================================\n");
        printf("Name:%s\nNIC:%s\nCategory:%s\nTotal Hours:%d\n\n", name, nic, category, total_hours);

        if (strncmp(category, "A1", 2) == 0) {
            pay_hour = 5;
        } else if (strncmp(category, "A2", 2) == 0) {
            pay_hour = 7;
        } else if (strncmp(category, "M1", 2) == 0) {
            pay_hour = 10;
        } else if (strncmp(category, "M2", 2) == 0) {
            pay_hour = 15;
        } else if (strncmp(category, "BB", 2) == 0) {
            pay_hour = 20;
        }

        if (total_hours > 44 && total_hours < 60) {
            gross_pay = straight_time * pay_hour;
            overtime_pay = pay_hour;
            net_pay = gross_pay + pay_hour;
            printf("Gross pay = %.2f RM\nOvertime pay =%.2f RM\nNet pay= %.2f RM\n", gross_pay, overtime_pay, net_pay);
            printf("\nContinue (Y/N) ? :");
            scanf("\n%c", &con);

        } else {
            printf("INPUT NOT VALID!!");
        }

    } while ((con != 'N'));
    getchar();
}
Lekensteyn
  • 64,486
  • 22
  • 159
  • 192

1 Answers1

0

Put a break statement after the line printf("INPUT NOT VALID!!"); to exit the loop instead of repeating it.

As for your other issue, Running fgets after a scanf can cause it to receive an empty line. See this question for the reason and solutions.

Community
  • 1
  • 1
interjay
  • 107,303
  • 21
  • 270
  • 254