将键盘输入模拟传递给控制台应用程序



我开发了简单的控制台菜单程序,该程序对键盘输入做出反应。

#include <iostream>
#include <cstdio>
using namespace std;

char* main_menu[] =
  {
    "1 - selection 1",
    "2 - selection 2",
    "3 - selection 3",
    "4 - selection 4",
    "q - quit",
    NULL
  };

char* menu2[] =
  {
    "a - selection a",
    "b - selection b",
    "c - selection c",
    NULL
  };

int getChoice( char* greet, char* choices[] )
{
  int chosen = 0;
  int selected;
  char** option;
  do
    {
      printf( "Choice: %sn", greet );
      option = choices;
      while (*option)
    {
      printf( "%sn", *option );
      option++;
    }
      do
    {
      selected = getchar();
      printf( "selected: %cn", selected );
    } while ( selected=='n' );
      option = choices;
      while (*option)
    {
      if ( selected == *option[0] )
        {
          chosen = 1;
          break;
        }
      option++;
    }
      if ( !chosen )
    {
      printf( "Incorrect choice, select againn" );
    }
    } while( !chosen );
  return selected;
}
int getAmount( char* greet )
{
  int amount = 0;
  printf( "%sn", greet );
  scanf("%d", &amount);
  return amount;
}


int main(int argc, char **argv, char **envp)
{
int choice = 0;
  do
    {
      choice = getChoice( "Please select an action", main_menu );
      printf( "You have chosen: %cn", choice );
    if ( choice == '1' )
    {
    printf( "choise 1");
    }
      else if ( choice == '2' )
    {
    printf( "choise 2");
    }
      else if ( choice == '3' )
    {
      int a = 0;
      a = getAmount( "type int value" );
      printf( "choise 3 entered %d",a);
    }
      else if ( choice == '4' )
    {
      int choice2 = 0;
      choice2 = getChoice( "Please select an action", menu2 );
      printf( "You have chosen: %cn", choice2 );
      if ( choice2 == 'a' )
        {
          printf( "choise a");
        }
      else if ( choice2 == 'b' )
        {
          printf( "choise b");
        }
      else if ( choice2 == 'c' )
        {
          printf( "choise c");
        }
    }
    } while ( choice != 'q' );
  }

我想通过它传递密钥序列以对其进行测试。我在 bash 中运行命令并期望按键 1:

回声 1 |。/选择器

但是得到了垃圾字符的非连续循环:选择:请选择一个操作

1 - selection 1
2 - selection 2
3 - selection 3
4 - selection 4
q - quit
selected: �
Incorrect choice, select again
Choice: Please select an action
1 - selection 1
2 - selection 2
3 - selection 3
4 - selection 4
q - quit
selected: �
Incorrect choice, select again
Choice: Please select an action

我的命令或程序有什么问题?

问题是,您不检查文件结尾。

selected = getchar();

应该是这样的:

if ((selected = getchar())== EOF){exit(0);}

相关内容

最新更新