我开发了简单的控制台菜单程序,可以对键盘输入做出反应。
#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: %s\n", greet );
option = choices;
while (*option)
{
printf( "%s\n", *option );
option++;
}
do
{
selected = getchar();
printf( "selected: %c\n", selected );
} while ( selected=='\n' );
option = choices;
while (*option)
{
if ( selected == *option[0] )
{
chosen = 1;
break;
}
option++;
}
if ( !chosen )
{
printf( "Incorrect choice, select again\n" );
}
} while( !chosen );
return selected;
}
int getAmount( char* greet )
{
int amount = 0;
printf( "%s\n", 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: %c\n", 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: %c\n", 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:
echo 1 | ./selector
但是得到了非连续循环的垃圾字符: 选择:请选择一个动作
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
我的命令或程序有什么问题?
答案 0 :(得分:0)
问题是,您没有检查文件结尾。
selected = getchar();
应该是这样的:
if ((selected = getchar())== EOF){exit(0);}