简体   繁体   中英

switch case not working properly in C

In my program there is a minor problem.

When I press 2 or 3 or 4 it will display the properly but after that when I press the a or b or c etc., it will display previous one result instead of print the Invalid option.

How can I fix this?

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

    typedef struct vehicle
    {
    char name[100];
    char lice_no[25];
    int vehicle_type;
    char cmpny_name[100];
    int menu_year;
     }record;

    int main(void)
    {
    int i,choice;
    FILE *fp1,*fp2;
    char oname[100];
    record det,det1;
    int recsize;
    char c;

    fp1 = fopen("record.dat" , "r+");
    if(fp1 == NULL)
    {
        fp1 = fopen("record.dat" , "w+");
        if(fp1 == NULL)
        {
            printf("error in opening file : \n");
            return -1;
        }
    }
    recsize = sizeof(det);

    do
    {
        printf("\t\"enter the choice\"\n");

        printf("1 : adding the record\n");
        printf("2 : delete the record\n");
        printf("3 : editing the record\n");
        printf("4 : display the record\n");
        printf("5 : exit the program\n");


        fflush(stdin);
        scanf("%d" , &choice);
        scanf("%c" , &c);

        switch(choice)
        {
            case 1 :
            {
                    printf("In this add logic\n")
                break;
            }
            case 2 :
            {
                printf("In this case delete logic\n");
                break;
            }
            case 3 :
            {
                printf("In this case edit logic\n");
                                break;
            }
            case 4 :
            {
                printf("display logic\n");
                break;
            }
            case 5 :
            {
                printf("exit logic\n");
                break;
            }
            default :
            {
                printf("\"Invalid option\"\n");
                break;
            }
        }
    }
    while(1);
    return 0;
}

It looks like you are getting the numbers into Choice, and the chars into c. but you are only using the Choice var in the switch, you are never checking the C var.

So essentially, if you hit a letter it is storing it in the C var, and then using the old value in Choice again.

Hmm, one of the things wrong in your codes is the:

scanf("%c" , &c);

because, the scanf function requires the user to press the enter key before it could store the character to its respective variable.

So if the compiler reads the line:

scanf("%c" , &c);

it reads your input, PLUS, the ENTER.
Thus forcing the scanf function to store your input, PLUS, the ENTER, into your character variable.

It would be better if you would use getche() or getch() instead of using scanf() function, and please do not ever use:

scanf("%c" , &c);

because it would generate an error.


Sample of usage of getche() or getch() function:

c=getche(); //waits for a keypress and stores it on a variable
c=getch();  //waits for a keypress and stores it on a variable

the difference between the two is that the getche() displays your keypress while the getch() does not.


Note: Do not forget to put

#include<conio.h>

Added info: If you still want to go on using the scanf() function just make sure that you declare your favorite variable as:

char c[20];

then you may use:

scanf("%s", &c);

but your variable, can only hold up to 19 characters, as how we declared on your character array.

And the summary is do not use:

scanf("%c", &c);

because, it can affect your other scanf() functions. :)


SOLUTION(Spoiler Warning):

#include <stdio.h>
#include <string.h>
#include <conio.h>

typedef struct vehicle
{
    char name[100];
    char lice_no[25];
    int vehicle_type;
    char cmpny_name[100];
    int menu_year;
}record;

int main(void)
{
    int i; //removed choice from int
    FILE *fp1,*fp2;
    char oname[100];
    record det,det1;
    char choice; //made the variable choice a character
    int recsize;
    char c;

fp1 = fopen("record.dat" , "r+");
if(fp1 == NULL)
{
    fp1 = fopen("record.dat" , "w+");
    if(fp1 == NULL)
    {
        printf("error in opening file : \n");
        return -1;
    }
}
recsize = sizeof(det);

do
{
    printf("\t\"enter the choice\"\n");

    printf("1 : adding the record\n");
    printf("2 : delete the record\n");
    printf("3 : editing the record\n");
    printf("4 : display the record\n");
    printf("5 : exit the program\n");


    fflush(stdin);
    choice = getche(); // or getch()

    switch(choice) //changed the target character
    {
        case '1' : //changed the case from 1 to '1'
        {
                printf("In this add logic\n");
                break;
        }
        case '2' : //changed the case from 2 to '2'
        {
            printf("In this case delete logic\n");
            break;
        }
        case '3' : //changed the case from 3 to '3'
        {
            printf("In this case edit logic\n");
                            break;
        }
        case '4' : //changed the case from 4 to '4'
        {
            printf("display logic\n");
            break;
        }
        case '5' : //changed the case from 5 to '5'
        {
            printf("exit logic\n");
            break;
        }
        default :
        {
            printf("\"Invalid option\"\n");
            break;
        }
    }
}
while(1);
return 0;
}

You can also use switch to compare characters. Just change the values

case 1:

to

case '1':

scanf returns you a value, which you don't check.

When used with %d specifier - it should parse an integer. Since you enter a non-integer value - scanf returns you an error code, and choice is unchanged

这是因为在c中,当您以整数形式读取字符时(scanf(“%d”,&choice);),如果需要,它将采用字符的ascii代码,例如a = 97,b = 98 c = 99 d = 100将a读为1 b并读为2,以此类推,您将必须添加一些额外的代码,以告诉程序该数字是否等于abcd的ascii码,或者将e减去96,从而得到1,2,3。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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