如何不使用else main()?

1 c if-statement

我正在写这段代码:

int main()
{
    char text[SIZE], choice[SIZE];
    printf("\nWelcome to Caesar's Cipher.\nDo you wish to encrypt or decrypt text?\n");
    fgets(choice, SIZE, stdin);
    if (strcmp(choice, "encrypt\n") == 0)
    { 
        printf("\nInsert text to encrypt:\n");
        fgets(text, SIZE, stdin);
        ciphering(text);
        printf("\nThis is your text encrypted with Caesar's Cipher:\n%s\n", text);
    }
    else if (strncmp(choice, "decrypt", 7) == 0)
    { 
        printf("\nInsert text to decrypt:\n");
        fgets(text, SIZE, stdin);
        deciphering(text);
        printf("\nThis is your text encrypted with Caesar's Cipher:\n%s\n", text);
    }
    else main();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是其他行main()看起来很丑陋而且不正确.我应该更改代码吗?如果是这样,怎么样?或者可以吗?

Eva*_*ran 8

此时应更换递归调用main与正常循环逻辑(do{ } while(...),while(...),for(...),等.

IIRC,呼叫main被认为是不正常的.因此,虽然编译器可能允许它,但它不是你应该做的事情.

如果我将你的代码转换为更传统的代码(针对相同的一般行为),我可能会写这样的:

int main(void)
{
    while(1) {
        char text[SIZE], choice[SIZE];
        printf("\nWelcome to Caesar's Cipher.\nDo you wish to encrypt or decrypt text?\n");

        fgets(choice, SIZE, stdin);

        if (strcmp(choice, "encrypt\n") == 0)
        { 
            printf("\nInsert text to encrypt:\n");
            fgets(text, SIZE, stdin);
            ciphering(text);
            printf("\nThis is your text encrypted with Caesar's Cipher:\n%s\n", text);
            break;
        }
        else if (strncmp(choice, "decrypt", 7) == 0)
        { 
            printf("\nInsert text to decrypt:\n");
            fgets(text, SIZE, stdin);
            deciphering(text);
            printf("\nThis is your text encrypted with Caesar's Cipher:\n%s\n", text);
            break;
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 你也可以'转到'.如果你敢. (2认同)
  • @black,你的孩子,但即使是`goto`也不是对'main`的递归调用更惯用的代码:-P (2认同)