*******************************************
* 书接上回 *
*******************************************
从键盘获取输入
几个函数:
int cbreak(void) 打开“中断模式”
int nocbreak(void) 关闭“中断模式”
crmode() 似与cbreak()功能相同
int echo(void) 打开回显
int noecho(void) 关闭回显
int getch(void)
int getstr(char *string)
int getnstr(char *string,int number_of_characters)
int scanw(char *format,......) 与scanf()类似
*********************************************************************************************************************
一段小程序,实现的功能是常用的输入用户名和密码:
/*passwordtest.c*/
#include <unistd.h>
#include <stdio.h>
#include <curses.h>
#include <string.h>
int main(int argc,char* argv[])
{
char name[20];
char password[20];
char *real_password="123456";
initscr();
move(5,10);
addstr("User name:");
getnstr(name,sizeof(name));/*获得输入*/
move(7,10);
addstr("Password:");
refresh();
cbreak();/*关闭中断*/
noecho();/*关闭回显*/
memset(password,0,sizeof(password));/*内存申请,并赋初值为空*/
//printw("/n%s",password);
int len = sizeof(password);
for(int i=0;i<len;i++)
{
password[i]=getch();
move(7,20+i);
addch('*');
refresh();
if(password[i]=='/n')
break;
if(strcmp(password,real_password)==0)
break;
}
echo();/*打开回显*/
nocbreak();
move(9,10);
if(strcmp(password,real_password)==0)
addstr("Correct");
else
addstr("Wrong");
//printw("/n%s",password);
refresh();
sleep(10);
endwin();
return 0;
}
编译gcc passwordtest.c -o passwordtest.o -lcurses -std=c99
注意:for循环在C99模式下才可使用,编译需要加上参数-std=c99
试试看~
*******************************************************************************************************************
在屏幕上显示一个字符,用户按上下左右键使字母移动
函数:
int keypad(WINDOW *window_ptr,bool keypad_on) keypad_on参数设置为true,然后调用keypad()函数来启用keypad模式
程序:
/*keypadtest.c*/
#include <curses.h>
#define MIN(a,b) a<b?a:b
#define MAX(a,b) a>b?a:b
int main(int argc,char* argv[])
{
int x=10;
int y=10;
char ch='A';
initscr();
crmode();
noecho();
clear();
keypad(stdscr,TRUE);
mvaddch(y,x,ch);
chtype input;
while((input=getch())&&input!=ERR &&input!='q')
{
if((input>='A'&&input<='Z')||(input>='a'&&input<='z'))
ch = input;
else{
switch(input){
case KEY_LEFT:
x=MAX(x-1,0);
break;
case KEY_RIGHT:
x=MIN(x+1,COLS);
break;
case KEY_UP:
y=MAX(y-1,0);
break;
case KEY_DOWN:
y=MIN(y+1,LINES);
break;
}
}
clear();
mvaddch(y,x,ch);
refresh();
}
endwin();
return 0;
}
编译 gcc keypadtest.c -o keypadtest.o -lcurses
**************************************************************************************************************************
by Naturalsd