c - 从 if 语句到 switch 语句?

标签 c if-statement switch-statement

我必须编写一个程序,将英语翻译成 pig 拉丁语,反之亦然,我不明白为什么在验证不接受字母输入后,它不会继续我的 switch 语句.这是我的代码的一部分:

int main()
{

    char choice;

    while (1) {

        printf("Press 1 to translate from English to pig Latin.\nPress 2 to translate from pig Latin to English.\nPress 3 to terminate the program.\nEnter your choice.\n");

        scanf("%s",&choice);

        if (isalpha (choice)) {
            printf ("ERROR: Please enter a valid input\n");
            continue;
        }

        switch (choice) {
            case 1:
                printf("Enter the English sentence.\n");
                scanf("%s",str);
                englishToPig();
                break;
            case 2:
                printf("Enter the pig Latin sentence.\n");
                scanf("%s",str);
                pigToEnglish();
                break;
            case 3:
                return 0;
            default:
                printf("Wrong Choice\n");
                break;
        }

    }

    return 0;
}

编辑:开关在技术上确实有效,但每当我输入 1、2 或 3 时,它会立即默认为“错误的选择”,而不是调用我的翻译功能(或退出程序)

最佳答案

我认为你应该使用int choice而不是使用char choice,然后将你的scanf%s%d

关于c - 从 if 语句到 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49787338/

相关文章:

c - 在 C 中通过引用将值从一个函数传递到另一个函数

c++ - 逻辑 CPU 计数返回 16 而不是 4

php - 如果列为空,在 php 中回显会出现错误

java - 为什么我会收到错误的 unreachable 语句?

c - switch 语句的问题

Swift 开关默认 + fallthrough : missing return in a function expected to return 'String'

c - 在C中使用linux串口,无法获取完整数据

.net - 在 .NET 中转换 long double

if-statement - 访问 typescript 联合类型中的不同属性

python if语句里面有语法错误