我必须写一个程序,将英语翻译成拉丁语,反之亦然,为一个介绍类,我不明白为什么在验证字母输入不被接受后,它不会继续我的开关语句。以下是我的代码:
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/