7. 输入函数

嗯,只有输出而没有输入是很无聊的。让我们看看允许我们从用户获取输入的函数。这些函数也可以分为三类。

  1. getch() 类:获取一个字符

  2. scanw() 类:获取格式化输入

  3. getstr() 类:获取字符串

7.1. getch() 函数类

这些函数从终端读取单个字符。但是有一些细微的事实需要考虑。例如,如果您不使用 cbreak() 函数,curses 不会连续读取您的输入字符,而只会在遇到换行符或 EOF 后才开始读取。为了避免这种情况,必须使用 cbreak() 函数,以便字符可以立即供您的程序使用。另一个广泛使用的函数是 noecho()。顾名思义,当设置(使用)此函数时,用户键入的字符不会显示在屏幕上。cbreak() 和 noecho() 这两个函数是按键管理的典型示例。此类函数在按键管理章节中进行了解释。

7.2. scanw() 函数类

这些函数类似于scanf(),但增加了从屏幕上的任何位置获取输入的功能。

7.2.1. scanw() 和 mvscanw

这些函数的使用方法类似于sscanf(),其中要扫描的行由wgetstr()函数提供。也就是说,这些函数调用wgetstr()函数(在下面解释)并使用结果行进行扫描。

7.2.2. wscanw() 和 mvwscanw()

这些函数与上面两个函数类似,不同之处在于它们从窗口读取,窗口作为这些函数的参数之一提供。

7.2.3. vwscanw()

此函数类似于vscanf()。当要扫描可变数量的参数时,可以使用此函数。

7.3. getstr() 函数类

这些函数用于从终端获取字符串。本质上,此函数执行与一系列调用以下函数相同的任务:getch(),直到收到换行符、回车符或文件结束符。生成的字符字符串由str指向,str 是用户提供的字符指针。

7.4. 示例

示例 4. 一个简单的 scanw 示例

#include <ncurses.h>			/* ncurses.h includes stdio.h */  
#include <string.h> 
 
int main()
{
 char mesg[]="Enter a string: ";		/* message to be appeared on the screen */
 char str[80];
 int row,col;				/* to store the number of rows and *
					 * the number of colums of the screen */
 initscr();				/* start the curses mode */
 getmaxyx(stdscr,row,col);		/* get the number of rows and columns */
 mvprintw(row/2,(col-strlen(mesg))/2,"%s",mesg);
                     		/* print the message at the center of the screen */
 getstr(str);
 mvprintw(LINES - 2, 0, "You Entered: %s", str);
 getch();
 endwin();

 return 0;
}