字符仅被视为无效

时间:2017-03-10 07:05:23

标签: c character

程序崩溃了,但没有解决。目前输入的每个字符在while循环中都返回无效。

char get_yes_or_no_character(void)
/*
  This is to purely get the Y or N for options
*/
{
  char choice = '\0';
  choice = printf("Would you like to use this roll for a game combination? Press Y for yes or N for no!\n");
  scanf(" %c", &choice);
  return choice;
}

char choice_input_validation(char choice)
/*
  This makes sure that input validation for the character is correct
*/
{
  while (choice != 'y' || choice != 'Y' || choice != 'n' || choice != 'N')
  {
    printf("Invalid option, try again\n");
    choice = printf("Would you like to use this roll for a game combination? Press Y for yes or N for no!\n");
    scanf(" %c", &choice);
  }
  return choice;
}

这是代码的片段

if (roll < 3)
{
  choice = get_yes_or_no_character();
  choice = choice_input_validation(choice);
}
if (choice == 'y' || choice == 'Y')
{
  break;
}

3 个答案:

答案 0 :(得分:2)

更改行:

scanf(" %c", choice);

到:

scanf(" %c", &choice);

scanf需要将指针作为参数。

同时更改while条件:

while (choice != 'y' || choice != 'Y' || choice != 'n' || choice != 'N')

到:

while ( (choice != 'y') && (choice != 'Y') && (choice != 'n') && (choice != 'N') )

如果 任何 之前的值,则要考虑choice无效。

答案 1 :(得分:0)

您使用此代码

while (choice != 'y' || choice != 'Y' || choice != 'n' || choice != 'N')
    {
        printf("Invalid option, try again\n");
        choice = printf("Would you like to use this roll for a game combination? Press Y for yes or N for no!\n");
        scanf(" %c", &choice);
    }
    return choice;

但是当任何人进入选择Y时,while的条件总是正确的,因为它不等于'y'。这就是它进入无限循环的原因。

答案 2 :(得分:0)

也是行

while (choice != 'y' || choice != 'Y' || choice != 'n' || choice != 'N') 

可能没有做你正在考虑的事情,因为选择总是不是这四个字符中的一个 - 所以它总是评估为真。

while (!( choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N'))

可能是这份工作(我自己也没有编译过)。