linux 对终端进行读写

以下代码摘自linux程序设计  英文名:beginning linux programming

#include <stdio.h>
#include <stdlib.h>
char *menu[] = {
"a - add new record",
"d - delete record",
"q - quit",
NULL,
};
int getchoice(char *greet,char *choices[]);
int main()
{
int choice = 0;
do
{
choice=getchoice("please select an action",menu);
printf("you have chosen: %c\n",choice);
}while(choice != 'q');
exit(0);
}

int getchoice(char *greet,char *choices[])
{
int chosen = 0;
{
int chosen = 0;
int selected;
char **option;
do{
        printf("choice: %s\n",greet);
        option=choices;
        while(*option)  //print menu
        {
                printf("%s\n",*option);
                option++;
        }
        do{
                selected = getchar();
        }while(selected == '\n');              
        option = choices;
        while(*option)
        {
                if(selected == *option[0])
                {
                        chosen = 1;
                        break;
                }

                        break;
                }
                option++;
        }
        if(!chosen)
        {
                printf("incorrect choice,select again\n");
        }
}while(!chosen);

return selected;
}

解释:linux is saving the input until the user presses Enter,and then passing

the choice character and the subsequent Enter to the program。

so,each time you enter a menu choice,the program calls getchar,processes the character,

then calls getchar again,which immediately returns with the Enter character。

Linux(like unix)uses a line feed to end lines of text.that is,uses a line feed alone to mean a newline,where

other systems,such as MS-DOS,use a carriage return and a line feed together as a pair.

解释性翻译:linux会暂存用户输入的内容,直到用户按下回车键。假设用户输入a,然后按下回车键。

第一次getchar得到a,第2次getchar得到'\n',linux用'\n'这一个字符来代替a newline,而MS-DOS用"\r\n"

注意:

以上代码中的

do{

selected = getchar();

}while(selected == '\n');

情景:用户输入a后回车

解读:在读到回车时,由于selected为'\n',故再次执行do语句,即执行第2次getchar,程序会等待用户输入。

巧妙的忽略了'\n'。

你可能感兴趣的:(linux 对终端进行读写)