简体   繁体   中英

C - Disable possibilities user already used

I couldn't find this anywhere...

I am making a project at my university - very simple. I have some questions/possibilities user can make... after using it, I want to disable it and never show so user can proceed in "while" loop to another.

Example:

while (something == true)
{
printf("Your possibilities are:\n 1 - Use a hammer\n 2 - Use a pipe\n 3 - Use a chair\n");

choice = getchar();

switch (choice)
{
  case '1':
    someCode();
    break;
  case '2':
    someCode();
    break;
  case '3':
    someCode();
    break;
}}

This is of course an example. Problem is, that after user used a hammer, some code will happen and then - I want only 2 possibilities: "pipe" and "chair". So next chance will be only "two-way" switch. In my code I have 6 possibilities and making bool for every choice and combine all six bools in if-else and then writting for each possibility a switch is unthinkable.

Is there any solution for this? Propably there is needed a bool variable for every possibility (if that is used) but I need to define that switch in some way.

Thanks!

Create a list of items and a parallel set of flags to keep track of what has been used.
Some pseudo code follows

#include <stdint.h>
#include <stdbool.h>

const char *item[] =
    { "a hammer", "a pipe", "a chair", "an awl", "an hour", 0 };
#define ITEM_N (sizeof item/sizeof item[0] - 1)

// return EOF on end-of-file/input error
// return 0 when no choices
// return 0 when non-numeric data entered
// return 0 when 0 or too high a value entered
// return 0 when a used value is selected
int Choice(bool *Used) {
  int choice = -1;
  puts("Your possibilities are:");
  for (int i = 0; item[i]; i++) {
    if (test_if_value_i_has_not_been_used) {
      print_prompt;
      choice = 0;
    }
  }
  if (choice < 0) {
    puts(" None");
    return 0;
  }
  char buf[50];
  read_user_input_into(buf);  // return EOF if no input
  if (!an_int_was_entered(&choice) ) return 0;
  if (choice_in_range) return 0;
  if (was_choice_used_before) return 0;
  Used[choice - 1] = true;
  return choice;
}

int main(void) {
  bool Used[ITEM_N] = { 0 };  // clear all flags
  while (Choice(Used))
    ;
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM