C Primer Plus 第十四章 编程练习10

作者在 2013-05-18 14:36:13 发布以下内容
/*
编写一个程序,用指向函数的指针数组执行菜单
例如,在菜单中选择a会激活由数组第一个元素指向的函数. 
*/

#include <stdio.h>
#include <ctype.h>

void a(void);
void b(void);
void c(void);
void d(void);

void menu(void);

int main(void)
{
	void (*p[4])(void) = {a, b, c, d};
	char ch;
	
	menu();

	while((ch = getchar()) && tolower(ch) != 'q')
	{
		switch(tolower(ch)){
			case 'a':p[0]();break;
			case 'b':p[1]();break;
			case 'c':p[2]();break;
			case 'd':p[3]();break;
		}
		menu();
		while(getchar() != '\n')
			continue;
	}
	return 0;
}

void a(void)
{
	printf("I am a().\n");
}

void b(void)
{
	printf("I am b().\n");
}

void c(void)
{
	printf("I am c().\n");
}

void d(void)
{
	printf("I am d().\n");
}

void menu(void)
{
	puts("a) 调用函数 a().");
	puts("b) 调用函数 b().");
	puts("c) 调用函数 c().");
	puts("d) 调用函数 d().");
	puts("q) 退出");
	printf("select:");
}
文章评论,共0条
游客请输入验证码
浏览39536次