Switch statement always including both the case and default

前端 未结 1 1570
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 06:17

When I compile this program, it outputs both the corresponding switch case and the default tag contents, the only value it doesn\'t print out for is January, any help would

相关标签:
1条回答
  • 2021-01-17 07:04

    You just need an extra case to handle the stray '\n' that comes from you pressing enter at your terminal. January should work if you just type 1

    Edit:Actually I just tested it on Linux and it works flawlessly, there might be some minor differences on Windows, though.

    while (month != EOF)
    {
            switch (month)
            {
    
                case 49:
                month2 = getchar();
    
                switch (month2)
                {
                    case 10:
                        printf("January \n");
                        break;
                    case 48:
                        printf("October \n");
                        break;
                    case 49:
                        printf("November \n");
                        break;
                    case 50:
                        printf("December \n");
                        break;
                }
                break;
    
                    case 50:
                        printf("February \n");
                        break;
                    case 51:
                        printf("March \n");
                        break;
                    case 52:
                        printf("April \n");
                        break;
                    case 53:
                        printf("May \n");
                        break;
                    case 54:
                        printf("June \n");
                        break;
                    case 55:
                        printf("July \n");
                        break;
                    case 56:
                        printf("August \n");
                        break;
                    case 57:
                        printf("Septembe \n");
                        break;
                    // Filter out stray \n
                    case '\n':
                        break;
                    default: printf("Error \n");
    
    
    
    
    
                }
                month = getchar();
    }
    
    
    system("PAUSE");
    return (0);
    
    0 讨论(0)
提交回复
热议问题