繁体   English   中英

带有switch语句的while循环没有退出

[英]While loop with switch statement in it not exiting

我的C代码有问题。 在运行代码时,即使它退出了开关并且满足了条件,它仍会停留在循环中。 你怎么解决这个问题? 这是代码。 `

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

int total(int x,int y,int z);
int male(int a,int b);
int female(int a,int b,int c,int d,int e);
void calories();

/*declaration of file pointers*/
FILE *fptr1;
FILE *fptr2;
FILE *fptr3;

char gender;

/*struct login data type*/
struct login {
    char username[10];
    char password[50];
};

/*struct clients data type*/
struct clients{
    char clientf_name[15];
    char clientl_name[20];
    };

/*struct calorie data type*/
struct calorie{
    int carbs;
    int protein;
    int fat;
};

/*struct bodyfat data type*/
struct bodyfat{
    int bodyweight;
    int waist;
    int wrist;
    int hip;
    int forearm;
};


int main()
{
    /*declaration of variables and constants*/
    struct login user;
    struct clients client;
    struct bodyfat percent;
    char login_user[10];
    char login_password[50];
    char str[100];
    char string[100];
    char client1[50];
    char stringline[150];
    char option;
    char choice;
    int condition = 1;
    int compare1 = 1;
    int compare2 = 1;
    int change;
    int bodyfat_percent;
/*opens files and assign them to a file pointer*/
    fptr1 = fopen("Usernames.txt","a+");
    fptr2 = fopen("Passwords.txt","a+");

    printf("Welcome!\n\n");//prints welcome message

    while((choice != 'Y') || (choice != 'y') || (choice !='N') || (choice != 'n')){
        system("cls");

        printf("Would you like to create an account? (Y-Yes/N-No)\n");
        scanf(" %c",&choice);

    /*switch case of persons choice*/
        switch(choice){
        /*if choice is 'Y' user enters name and password for their account*/
                case 'y':
                case 'Y':system("cls");
                        printf("Please enter the name you would like\n");
                        scanf("%s", user.username);
                        printf("Please enter the password you would like\n");
                        scanf("%s",user.password);
                        fprintf(fptr1,"%s",user.username);
                        fprintf(fptr1,"\n");
                        fprintf(fptr2,"%s",user.password);
                        fprintf(fptr2,"\n");
                        printf("Press Enter to continue...\n");
                        getch();
                        break;
        /*if choice is 'N' user decides whether to exit or continue to login*/
                case 'n':
                case 'N':while ((choice != 'Y') || (choice != 'y') || (choice != 'N') || (choice != 'n'))
                            {
                            system("cls");
                            printf("Would you like to exit (Y-Yes/N-No)?\n");
                            scanf(" %c",&choice);
                            switch(choice){
                                case'y':
                                case'Y':system("cls");
                                        printf("Program is exiting Good bye!\n");
                                        exit(0);
                                case'n':
                                case'N':printf("Press Enter to continue to login....\n");
                                        getch();
                                        break;
                                default:printf("Incorrect entry. Press Enter to try again\n");
                                        getch();
                                        break;
                            }
                        }
                        break;
                default: printf("Incorrect entry. Press Enter to try again/n");
                        getch();
                        break;
            }
    }
    fclose(fptr1);
    fclose(fptr2);


/*check if files were open or not*/
    if((fptr1 = fopen("Usernames.txt","r"))== NULL){
            printf("File was not opened\n");
        }
    if((fptr2 = fopen("Passwords.txt","r"))== NULL){
            printf("File was not opened\n");
        }
    /*do-while loop to log in to account*/
    do{
        system("cls");
        printf("Enter username:");
        scanf("%s",login_user);
        printf("Enter password:");
        scanf("%s",login_password);
   /*while loop to read strings from file and compare*/
        while(compare1 != 0){
            fscanf(fptr1,"%s",str);
            compare1 = strcmp(str,login_user);
        }
        while(compare2 != 0){
            fscanf(fptr2,"%s",string);
            compare2 = strcmp(string,login_password);
        }
    /*if statement that checks if compare 1 and compare 2 is equal to 0*/
        if((compare1 == 0)&&(compare2 == 0)){
            printf("\nWelcome %s\n",login_user);
        }else{
            printf("incorrect username or password please try again");
        }
    }while((compare1 != 0) && (compare2 != 0));
    fclose(fptr1);
    fclose(fptr2);

    /*while loop*/
    while(1){//1 is used in the while loop to make it an infinite loop
        system("cls");
        printf("Choose an option below\n");
        printf("A.Add client\n");
        printf("B.Calculate calories\n");
        printf("C.Body fat calculator\n");
        printf("D.Exit\n");
        scanf(" %c",&option);

        /*switch function*/
        switch(option)
        {
            /*if option is A user inputs client's information*/
            case 'A':system("cls");
                     fptr3 = fopen("Clients.txt","a");
                     printf("Please enter clients first name\n");
                     scanf("%s",client.clientf_name);
                     printf("Please enter clients last name\n");
                     scanf("%s",client.clientl_name);
                     /*while loop to get users body weight, waist size,
                     wrist size, hip size and forearm size based on gender*/
                     while(condition == 1){
                        printf("Please enter clients gender (M/F)\n");
                        scanf(" %c",&gender);
                        if(((gender == 'M')||(gender == 'm'))){
                           printf("Please enter bodyweight(lbs)\n");
                           scanf("%d",&percent.bodyweight);
                           printf("Please enter waist size\n");
                           scanf("%d",&percent.waist);
                           printf("Press Enter too continue....\n");
                           getch();
                           condition = 0;//condition changed to 0 to end loop;
                        }else if((gender == 'F')||(gender == 'f')){
                            printf("Please enter bodyweight(lbs)\n");
                            scanf("%d",&percent.bodyweight);
                            printf("Please enter waist size\n");
                            scanf("%d",&percent.waist);
                            printf("Please enter wrist size\n");
                            scanf("%d",&percent.wrist);
                            printf("Please enter hip size\n");
                            scanf("%d",percent.hip);
                            printf("Please enter forearm size\n");
                            scanf("%d",percent.forearm);
                            printf("Press Enter to continue...\n");
                            getch();
                            condition = 0;//condition changed to 0
                        }
                     }
                     /*store values to file*/
                     fprintf(fptr3,"%s %s\n",client.clientf_name,client.clientl_name);
                     fprintf(fptr3,"%c \n",gender);
                     fprintf(fptr3,"bodyweight:%d lbs\n",percent.bodyweight);
                     fprintf(fptr3,"waist:%d inches\n",percent.waist);
                     fprintf(fptr3,"wrist:%d inches\n",percent.wrist);
                     fprintf(fptr3,"hip:%d inches\n",percent.hip);
                     fprintf(fptr3,"forearm:%d inches\n",percent.forearm);
                     fclose(fptr3);
                     break;
            /*if case B calories function calculates calories*/
            case 'B':system("cls");
                     calories();
                     break;
            /*if case C based on gender the body fat percentage is calculated*/
            case 'C':if((gender == 'M') || (gender == 'm')){//gender is male calculate body fat percentage using body weight and waist size
                        fptr3 = fopen("Clients.txt","a");
                        system("cls");
                        printf("Enter body weight (Lbs):");
                        scanf(" %d",&percent.bodyweight);
                        printf("Enter waist measurement:");
                        scanf(" %d",&percent.waist);
                        bodyfat_percent = male(percent.bodyweight,percent.waist);//male function to calculate body fat percentage for males
                        printf("your body fat percentage is: %d",bodyfat_percent);
                        fprintf(fptr3,"body fat percentage is: %d\n",bodyfat_percent);
                        printf("Press Enter to go back to menu...");
                        getch();
                        fclose(fptr3);
                     }else if((gender == 'F') || (gender == 'f')){//gender is female calculate the body fat percentage with
                         //body weight, waist size, wrist size, hip size and forearm size
                        fptr3 = fopen("Clients.txt","a");
                        system("cls");
                        printf("Enter body weight:");
                        scanf(" %d",&percent.bodyweight);

                        printf("Enter wrist measurement:");
                        scanf(" %d",&percent.wrist);

                        printf("Enter waist measurement:");
                        scanf(" %d",&percent.waist);

                        printf("Enter hip measurement:");
                        scanf(" %d",&percent.hip);

                        printf("Enter forearm measurement:");
                        scanf(" %d",&percent.forearm);

                        bodyfat_percent = female(percent.bodyweight,percent.wrist,percent.waist,percent.hip,percent.forearm);//female function to calculate BFP for females
                        fprintf(fptr3,"body fat percentage is: %d\n",bodyfat_percent);
                        printf("Body fat percent is: %.1f\%\n",bodyfat_percent);
                        }
                        fclose(fptr3);
                        break;
            /*if case is D exit program*/
            case 'D':printf("Program is exiting. Good Bye!");
                     exit(0);
                     break;
        }
    }
    getchar();
    getchar();
    getchar();
    return 0;//returns 0 if code runs successful
}

/*total function that calculates the total calorie intake for the day*/
int total(int x,int y,int z){
    x = x*4;
    y = y*4;
    z = z*9;
    int c = x + y + z;
    return c;
}

/*male function that calculates body fat percentage for male clients*/
int male(int a,int b){
    int c = (a * 1.082) + 94.42;
    int d = b * 4.15;
    int e = c - d;
    int f = a - e;
    int g = (f * 100)/a;
    return g;
}

/*female function that calculates body fat percentage for female clients*/
int female(int a,int b,int c,int d,int e){
    int f = (a * 0.732) + 8.987;
    int g = b / 3.140;
    int h = c * 0.157;
    int i = d * 0.249;
    int j = e * 0.434;
    int k = f + g - h - i + j;
    int l = a - k;
    int m = (l * 100)/a;
    return m;
}

/*calories function that calculates the total number of
calories for each day of the week and displays its average at the end of the week*/
void calories(){
    int day = 1;
    int total_intake = 0;
    int intake_per_day[7];
    int avg;
    int i = 1;
    struct calorie intake;
    FILE *fptr3;
    if((fptr3 = fopen("Clients.txt","a"))==NULL){
        printf("File was not opened\n");
    }
    for(day = 1; day < 7; day++){
        system("cls");
        printf("Please enter carbohydrate intake:");
        scanf(" %d",&intake.carbs);

        printf("Please enter protein intake:");
        scanf(" %d",&intake.protein);

        printf("Please enter fat intake:");
        scanf(" %d",&intake.fat);

        intake_per_day[i] = total(intake.carbs,intake.protein,intake.fat);
        fprintf(fptr3,"Day    Carbohydrates    Proteins    Fats    Total\n");
        fprintf(fptr3,"%d     %d               %d          %d       %d\n",day,intake.carbs,intake.protein,intake.fat,total_intake);
        i++;
    }
    for(i = 1;i < 7;i++){
        total_intake = total_intake + intake_per_day[i];
    }
    avg = total_intake / 7;
    fprintf(fptr3,"average intake for the week is: %d\n",avg);
    fclose(fptr3);
}

`

中的逻辑

while((choice != 'Y') || (choice != 'y') || (choice !='N') || (choice != 'n')){

有缺陷。

无论输入是什么,它将评估为true。 对于任何输入,这些条件中的至少三个将成立。

如果要强制用户输入YyNn ,则需要使用use &&代替||

while((choice != 'Y') && (choice != 'y') && (choice !='N') && (choice != 'n')){

另外, choice在首次使用前不会初始化。 我的建议:

创建函数get_choiceis_valid_choice
main调用get_choice 您可以拨打is_valid_choice无论从mainget_choice

bool is_valid_choice(char choice)
{
   return (choice == 'Y' || choice == 'y' || choice == 'N' || choice == 'n');
}

char get_choice()
{
   char choice;
   while ( scanf(" %c", &choice) > 0 && !is_valid_choice(choice));
   return choice;
}

main

char choice = get_choice();

// Use choice as you see fit.

因为使用||所以循环条件将始终为true。 您打算在何处使用&&运算符。 choice每个可能值都不等于'y''Y'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM