继续循环不能正常工作

时间:2014-05-31 22:59:42

标签: c loops continue

我在下面的程序中有两个继续循环 - 每次当用户输入'X'或'x'时,程序应该再次询问用户输入,即程序应该保持正常工作。但是,在我的程序中,在输入X / x时,它会终止。

我真的很感激为什么会这样做的建议!

#include<stdio.h>
int main(int argc, char const *argv[])
{
    char card_name[3];
    int count = 0;
    while (card_name[0] != 'X')  
    {
        printf("\n Enter the card name\n");
        scanf("%2s", card_name);
        int val = 0;
        switch (card_name[0])
        {
        case 'K':
        case 'Q':
        case 'J': val = 10;
            break;
        case 'A': val = 11;
            break;
        case 'x':
        case 'X':
            printf("\n Game ended, thanks for playing!!!\n");
            printf("\n New Game begins!!!\n");
            continue;

        default: val = atoi(card_name);
            //break;
            if ((val < 1) || (val > 10))
            {
                printf("\n Incorrect card name entered! Please try again!\n");
                continue;
            }
        }

        printf("\n The current card value is:%i\n", val);

        //Card counting
        if ((val > 2) && (val < 7))
        {
            count++;
            printf("\n The count has gone up\n");
        }
        else if (val == 10)
        {
            count--;
            printf("\n The count has gone down\n");
        }

        printf("\n The current card count is %i\n", count );
    } 
    /* code */
    return 0;
}

2 个答案:

答案 0 :(得分:3)

如果输入大写X,则continue会返回循环条件;

while(card_name[0]!='X')

...其中值为X并且它会立即退出。

答案 1 :(得分:0)

变化:

    case 'x':
    case 'X':
        printf("\n Game ended, thanks for playing!!!\n");
        printf("\n New Game begins!!!\n");
        continue;

为:

    case 'x':
    case 'X':
        printf("\n Game ended, thanks for playing!!!\n");
        printf("\n New Game begins!!!\n");
        *card_name = '\0';
        continue;