简体   繁体   中英

C: switch statement not working?

Ok, so fgets reads lines from file redirection input and then uses those lines to evaluate a switch statement.
I am trying to test case '1' however it is not working.
This is my output: DATA SET ANALYSIS 1. Show all the data 2. Calculate the average for an experiment 3. Calculate the average across all experiments 4. Quit Selection: 1

Does anyone understand why none of my switch statement is running? Clearly var is equal to 1, so the switch should be at the very least printing HELLO , however it does nothing. Help?

while(fgets(str,100,stdin) != NULL && (strcmp(str,"4") && strcmp(str,"4\n")))
    {
        var = atoi(str);
        printf("DATA SET ANALYSIS\n1.\tShow all the data\n2.\tCalculate the average for an experiment\n3.\tCalculate the average across all experiments\n4.\tQuit\nSelection: %d\n",var);
        switch(var)
        {
        case '1' :
            printf("HELLO\n");
            for(j=0;j<i;j++)
            {
                printf("%s",experiments[j]);
                for(k=0;k<10;k++)
                {
                    printf("%d ",data[j][k]);
                }
                printf("\n");
            }
            break;
        }
    }
case '1' :

'1' is the character 1 (ASCII 49), not the integer 1, change it to:

case 1 :

Note that character literals like '1' has type int in C, so the syntax is correct, but not the behavior you expected.

(int) var is compared to ascii '1'

    var = atoi(str);
    printf("DATA SET ANALYSIS\n1.\tShow all the data\n2.\tCalculate the average for an experiment\n3.\tCalculate the average across all experiments\n4.\tQuit\nSelection: %d\n",var);
    switch(var)
    {
    case '1' :

change your case to

    case 1:

The character '1' has the ascii value 49. When doing case '1' you are actually doing in your case

    case 49:

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