linux 对终端读写,linux 对终端进行读写

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

#include

#include

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'。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值