Постановка задачи: Напишите программу, которая сначала по первой букве должности, введен- ной пользователем, определяет соответствующее значение переменной, помещает это значение в переменную типа etype, а затем выводит полностью название должности, первую букву которой ввел пользователь. Взаимодействие программы с пользователем может выглядеть следующим образом: Введите первую букву должности (laborer, secretary, manager, accountant, executive, researcher); a полное название должности: accountant
Как я это реализовал:
#include <iostream>
#include <conio.h>
using namespace std;
enum etype { laborer, secretary, manager, accountant, executive, researcher
};
int main()
{
char ch;
etype word;
cout << "Enter first letter posts \n";
cout << "(laborer, secretary, manager, accountant, executive,
researcher); ";
ch = _getche();
switch (ch)
{
case 'l': word = laborer; cout << "\nFull name post: " << word << endl;
break;
case 's': word = secretary; cout << "\nFull name post: " << word << endl;
break;
case 'm': word = manager; cout << "\nFull name post: " << word << endl;
break;
case 'a': word = accountant; cout << "\nFull name post: " << word <<
endl; break;
case 'e': word = executive; cout << "\nFull name post: " << word << endl;
break;
case 'r': word = researcher; cout << "\nFull name post: " << word <<
endl; break;
default: cout << "\nThe post not found!"; break;
}
system("pause");
return 0;
}
Но как и ожидаемо, выводятся цифры, вместо названий. Но я не пойму, как сделать так, чтобы выводились названия. В голову приходит только прописывать их вручную в cout в кавычках...
А зачем вообще так длинно? Можно и без этого switch... Вот, примерно так (просто наброски! чтоб понять идею, а не чтоб броситься компилировать как есть...)
enum etype
{
laborer = 0, secretary, manager, accountant, executive, researcher
};
const char firstLetters[] = "lsmaer";
const char * position[] = {
"laborer", "secretary", "manager", "accountant", "executive", "researcher"
};
...
ch = _getche();
// Ищем, есть ли введенная буква среди первых букв
char * who = strchr("lsmaer",ch);
// если нет - сообщаем об ошибке, и идем заново.
if (who == 0) cout << "Wrong input\n"; // И к началу цикла ввода
// Какая буква по счету - та и профессия (enum - это же просто число)
word = who - firstLetters;
// Выводим название профессии
cout << "Position: " << position[word] << "\n";
Компилируемый пример.
#include <iostream>
#include <conio.h>
using namespace std;
enum etype { laborer = 0, secretary, manager, accountant, executive, researcher };
struct Position
{
etype code;
char * name;
}
positions[] = {
#define ITEM(x) { x, #x }
ITEM(laborer), ITEM(secretary), ITEM(manager),
ITEM(accountant), ITEM(executive), ITEM(researcher)
};
int main()
{
Position word;
cout << "Enter first letter (";
for(auto pos = begin(positions); pos != end(positions); ++pos)
{
if (pos != begin(positions)) cout << ", ";
cout << pos->name;
}
cout << "): ";
char ch = _getche();
bool found = false;
for(auto pos : positions)
if (pos.name[0] == ch)
{
word = pos; found = true; break;
}
if (found)
cout << "\n\nFull name is " << word.name << endl;
else
cout << "\n\nWrong input\n";
system("pause");
}
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости