C程序如何实现输入一个字符串,随时可以按ESC健退出?

zzybird 2012-09-11 09:57:10
C程序如何实现输入一个字符串,用户按回车后读入字符串,输入过程中用户随时按ESC健可以退出?
原来我用getche()的循环来实现,但这种实现方法导致退格键等功能键失效。有没有方法能够实现上面功能,又能保证用户输入时功能键可以正常使用?
...全文
774 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
manxiSafe 2012-09-19
  • 打赏
  • 举报
回复
还是这几个回复,没看到 简单的啊。
「已注销」 2012-09-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

getchar()
scanf("%s[^0x1B]",str); // ESC的ASCII码是0x1B
[/Quote]getchar()已经取走缓冲区的字符了,而你的scanf是个正则表达,表示输入字符串到str中,指导遇到0x1B停止截断数据,而且你还写错了,是%[^0x1B]

xxx = getch();
xxx = getchar();
一个不回显一个回显,退格必须自己处理。
manxiSafe 2012-09-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
getchar()
scanf("%s[^0x1B]",str); // ESC的ASCII码是0x1B
[/Quote]

这样不行吧。
pathuang68 2012-09-11
  • 打赏
  • 举报
回复
楼主如果用tc的话,可以利用一下bioskey之类的函数。
在vc中的话,可以考虑kbhit这个函数
aozhi 2012-09-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
getchar()
scanf("%s[^0x1B]",str); // ESC的ASCII码是0x1B
[/Quote]
能这么写吗?表示怀疑。
图灵狗 2012-09-11
  • 打赏
  • 举报
回复
以下代码在Linux上测试成功,稍微注意Windows上的\r\n会稍有不同:

int main(int argc, char* argv[])
{
char str[81];
char ch = 0;
int i = 0;

while(1)
{
ch = getch();
if(ch == 0x1b)
{
break;
}
putchar(ch);
if(ch == '\r' || ch == '\n')
{
str[i] = '\0';
printf("%s\n", str);
i = 0;
}
else
{
str[i++] = ch;
}
}

return 0;
}
阳光陷阱 2012-09-11
  • 打赏
  • 举报
回复
getchar()
scanf("%s[^0x1B]",str); // ESC的ASCII码是0x1B
图灵狗 2012-09-11
  • 打赏
  • 举报
回复
Windows下注意换行符的问题即可:

int main(int argc, char* argv[])
{
char str[81];
char ch = 0;
int i = 0;

while(1)
{
ch = getch();
if(ch == 0x1b)
{
break;
}
putchar(ch);
if(ch == '\r' || ch == '\n')
{
str[i] = '\0';
printf("%s\n", str);
i = 0;
}
else
{
str[i++] = ch;
}
}

return 0;
}
xspace_time 2012-09-11
  • 打赏
  • 举报
回复
尽情的输入 只是还没搞好当需要极大内存时该怎么写 也许可以用文件缓存 只是现在看起来没必要

#include<stdio.h>
#include<conio.h>
int main()
{
unsigned char s[1024]={0};
int i=0,l;
while((s[i]=getch())!=0x1b)
{
if(s[i]==0x0d)
{
puts("");
i++;
}

printf("%c",s[i]);
i++;
}
puts("");
printf("共%d个字符\n",i);
l=i;i=0;
while(i<l)
{
if(s[i]==0x0d)
{
puts("");
i++;
}
printf("%c",s[i]);
i++;
}
puts("");
return 1;
}
赵4老师 2012-09-11
  • 打赏
  • 举报
回复
仅供参考
#include <conio.h>
#include <stdio.h>
char pw[40];
int i,ch;
FILE *f;
void main() {
cprintf("\r\nPassword:");
i=0;pw[i]=0;
while (1) {
ch=getch();
if (ch==13 || i>=39) break;
switch (ch) {
case 27:
cprintf("\rPassword: %40s"," ");
cprintf("\rPassword: ");
i=0;pw[i]=0;
break;
case 8:
if (i>0) {
i--;
pw[i]=0;
cprintf("\b \b");
}
break;
default:
pw[i]=ch;
i++;
pw[i]=0;
cprintf("*");
break;
}
}
cprintf("\r\n");
f=fopen("password.txt","w");
fprintf(f,"%s\n",pw);
fclose(f);
}

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧