How would I get this to work? I get the error code that the letters are not declared, also how do I get the function to quit when they press Q?
char getChoice(char* choice)
{
printf("\nEnter the R, P, S, or Q (for quit) ");
scanf("%c", choice);
switch(*choice){
case R:
printf("You picked Rock, ");
break;
case P:
printf("You picked Paper, ");
break;
case S:
printf("You picked Scissors, ");
break;
case Q:
default:
printf("Error: Invalid choice, try again.");
break;
}
return *choice;
}
答案 0 :(得分:1)
First put the letters after case
between '
.
Second: modify que 'Q' case like this:
Change switch(*choice)
to switch(choice)
. scanf
wants a pointer and choice
is already a pointer.
char getChoice(char* choice)
{
...
case 'Q':
return 0;
break;
default:
printf("Error: Invalid choice, try again.");
break;
}
Depending on how you call GetChoice
you might return
another value than 0
.
There may be more issues depending on how you call getChoice
.
答案 1 :(得分:0)
You can edit your case statement like this;
switch(*choice)
{
case 'R':
printf("You picked Rock, ");
break;
case 'P':
printf("You picked Paper, ");
break;
case 'S':
printf("You picked Scissors, ");
break;
case 'Q':
default:
printf("Error: Invalid choice, try again.");
break;
}
Hope this helps.
答案 2 :(得分:0)
这是一个彻底改进的get_choice
:
#include <stdlib.h> // for exit
char get_choice() {
char choice;
while (1) {
printf("\nEnter the R, P, S, or Q (for quit) ");
if (scanf("%c", &choice) != 1) {
printf("Error reading a character!\n");
exit(1);
}
switch(choice){
case 'r':
printf("You picked Rock, ");
goto exit;
case 'p':
printf("You picked Paper, ");
goto exit;
case 's':
printf("You picked Scissors, ");
goto exit;
case 'q':
exit(0);
default:
printf("Error: Invalid choice, try again.");
break;
}
}
exit:
return choice;
}
(并且exit
位于<stdlib.h>
)
首先,现在您不需要传递指向char的指针来保存选择;它是在函数内部完成的。其次,我们对case标签使用字符常量 - 小写,因为这可能是用户宁愿写的东西。我们循环直到给出一个合适的值;如果给出,我们会使用exit
跳转到goto
标签。我们还检查scanf
的返回值,如果没有字符可以读取(文件结束?),就会挽救