循环错误,程序停止并显示“INPUT NOT VALID !!”但再次询问输入?

时间:2013-12-16 16:59:40

标签: c loops if-statement do-while

我有这两个问题:

  1. 我有这段代码需要花费数小时。如果total_hours大于60,那么它应该停止。它确实停止,但随后显示消息INPUT NOT VALID!!并再次请求输入(不应该输入。)
  2. 否则,在第二次“当使用把”Y“作为答案”时,不会询问第一个名为“name”的输入。
  3. 代码:

    #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();
    }
    

1 个答案:

答案 0 :(得分:0)

break行后面添加printf("INPUT NOT VALID!!");语句,退出循环而不是重复循环。

至于您的其他问题,在fgets之后运行scanf会导致它收到空行。有关原因和解决方案,请参阅this question