我必须编写一个程序,将英语翻译成 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/