如何限制字符输入范围?

时间:2019-07-10 17:37:59

标签: c++ assembly visual-c++

问题指出,

  

get_char子例程允许输入任何字符。使用汇编程序修改get_char以仅接受“ 0”和“ z”范围内的ASCII字符。您还需要接受“ $”作为有效输入(终止符)。如果输入了无效字符,则应继续要求输入新的字符,直到给出一个新的字符为止,并另外显示错误消息“仅字母数字字符,请重试>”。

void get_char(char& a_character)
{
  a_character=(char) _getwche();
  if (a_character=='0' || a_character=='z')  // allow the enter key to work as the terminating character too
    a_character=dollarchar;
}

1 个答案:

答案 0 :(得分:0)

我没有汇编代码,但是在C语言中,您显示的get_char()函数需要看起来更像以下内容:

void get_char(char& a_character)
{
  do
  {
    a_character = (char) _getwche();
    if (
      ((a_character >= '0') && (a_character <= '9')) ||
      ((a_character <= 'a') && (a_character <= 'z')) ||
      ((a_character <= 'A') && (a_character <= 'Z')) ||
      (a_character == dollarchar)
      )
    /* alternatively:
    if (isalnum(a_character) || (a_character == dollarchar))
    */
    {
      break;
    }

    printf("Alphanumeric characters only, please try again > ");
  }
  while (true);
}

或者:

void get_char(char& a_character)
{
  a_character = (char) _getwche();
  while (
    !(
      ((a_character >= '0') && (a_character <= '9')) ||
      ((a_character <= 'a') && (a_character <= 'z')) ||
      ((a_character <= 'A') && (a_character <= 'Z')) ||
      (a_character == dollarchar)
      )
    )
  /* alternatively:
  while (!isalnum(a_character) && (a_character != dollarchar))
  */
  {
    printf("Alphanumeric characters only, please try again > ");
    a_character = (char) _getwche();
  }
}

我将其保留为练习,以将C代码转换为程序集。