📄 dog.cpp
字号:
/*
dog.cpp -- A program demonstrating function pointers.
*/
#include <stdio.h>
#include <iostream.h>
#include <string.h>
const char *Commands[] =
{
"come", "done", "fetch", "heel",
"sit", "speak", "stay"
};
#define COMMANDS (sizeof (Commands) / sizeof (char *))
// Declare our functions
void Come(), Done(), Fetch(), Heel();
void Sit(), Speak(), Stay();
// Put the functions in an array of functions
void (*Command[])(void) =
{Come, Done, Fetch, Heel, Sit, Speak, Stay};
// Binary search function
int Binary (char *In);
int main ()
{
int Action = 0;
int Done;
Done = Binary ("done");
if (Done < 0)
{
cerr << "Cannot find exit command" << endl;
return (-1);
}
//
// Make sure the function table isn't too small. Jumping
// to an undefined spot can be dangerous.
if (COMMANDS > (sizeof(Command)/sizeof(void(*)(void))))
{
cerr << "Function table is too short" << endl;
return (-1);
}
do
{
char In[128];
cout << "Please enter a command: ";
cin >> In;
Action = Binary (In);
if (Action < 0)
{
cout << "Valid commands are" << endl;
for (int x = 0; x < COMMANDS; ++x)
cout << '\t' << Commands[x] << endl;
continue;
}
Command[Action]();
} while (Action != Done);
return (0);
}
int Binary (char *In)
{
int low = 0;
int high = COMMANDS - 1;
int mid, check;
strlwr (In);
while (low <= high)
{
mid = (low + high) / 2;
if (!(check = strcmp (In, Commands[mid])))
return (mid);
if (check < 0)
high = mid - 1;
else
low = mid + 1;
}
return (-1);
}
void Done ()
{
cout << "Your dog licks your face in enormous ";
cout << "gratitude" << endl;
}
void Sit()
{
cout << "Your dog is now sitting" << endl;
}
void Stay()
{
cout << "Your dog stays put (good dog!)" << endl;
}
void Come()
{
cout << "Your dog is running toward you" << endl;
}
void Fetch()
{
cout << "You toss a stick and your dog runs after it";
cout << endl;
}
void Heel()
{
cout << "Your dog walking by your side" << endl;
}
void Speak()
{
cout << "\"Arf!\" says Sandy" << endl;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -