Реализовать меню с использованием стрелок - C (СИ)
Формулировка задачи:
Помогите транслировать код из Паскаль в Си. Попросту говоря, это обычное меню с использованием стрелок.
program projectX;
uses crt;
CONST
m:array[1..3] of string=('Show the task',
'Start calculations',
'Exit');
VAR
i,x,y,menuItem:integer;
c:char;
x:=30; y:=10;
menuItem:=1;
repeat
clrscr;
for i:=1 to 3 do
begin
gotoXY(x,y+i);
if i=menuItem then
begin
textColor(0);
textBackGround(15);
end
else
begin
textColor(15);
textBackGround(0);
end;
write(m[i]);
end;
c:=readkey;
case c of
#72: if menuItem=1 then
menuItem:=3
else dec(menuItem);
#80: if menuItem=3 then
menuItem:=1
else inc(menuItem);
#13: case menuItem of
1: ShowTask;
2: Calc;
3: break;
end;
end;
until c=#27;
END.Решение задачи: «Реализовать меню с использованием стрелок»
textual
Листинг программы
#include <stdio.h>
#include <windows.h>
void gotoxy(int x, int y) {
COORD coord = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void textcolor(short f, short b) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), f | (b << 4));
}
char getch() {
HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD rec;
DWORD event;
FlushConsoleInputBuffer(hstdin);
while (ReadConsoleInputA(hstdin, &rec, 1, &event)) {
if ((rec.EventType == KEY_EVENT)
&& (rec.Event.KeyEvent.bKeyDown)) {
return rec.Event.KeyEvent.wVirtualKeyCode;
}
}
return EOF;
}
int menu(int x, int y, const char* items[], int cnt) {
const short COLOR_FG = 7;
const short COLOR_BG = 0;
int i;
char ch;
textcolor(COLOR_FG, COLOR_BG);
for (i = 0; i < cnt; ++i) {
gotoxy(x, y + i);
printf("%s", items[i]);
}
i = 0;
gotoxy(x, y); textcolor(COLOR_BG, COLOR_FG);
printf("%s", items[i]);
while (((ch = getch()) != EOF) && (ch != VK_RETURN)) {
gotoxy(x, y + i); textcolor(COLOR_FG, COLOR_BG);
printf("%s", items[i]);
switch (ch) {
case VK_ESCAPE:
return 0;
case VK_UP:
i = (i == 0) ? (cnt - 1) : (i - 1);
break;
case VK_DOWN:
i = (i == cnt - 1) ? 0 : (i + 1);
break;
}
gotoxy(x, y + i); textcolor(COLOR_BG, COLOR_FG);
printf("%s", items[i]);
}
textcolor(COLOR_FG, COLOR_BG);
return i + 1;
}
int main() {
const char* items[] = {"Show the task",
"Start calculations",
"Exit"};
int i = menu(3, 3, items, 3);
gotoxy(3, 7);
printf("Return: %d\n\n", i);
system("pause");
return 0;
}