我试图“捕获”用户的键盘输入,这意味着代码将阻止他们输入某些字符,在这种情况下会阻止输入数字和特殊字符。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
char buffer[30];
void in_text();
int main(void)
{
in_text();
printf ("\nThe string you entered is: %s", buffer);
return 0;
}
void in_text(void)
{
char buffe[30];
char c1;
int x = 0, hit = 0;
printf("Enter string: ");
while (hit!=1)
{
c1 = getch();
if (c1=='\b' && x!=0)
{
buffe[--x] = '\0';
printf ("\b \b");
}
if (isalpha(c1) || isspace(c1) && c1!='\r')
{
buffe[x++] = c1;
buffe[x+1] = '\0';
printf("%c", c1);
}
if (c1=='\r' && strlen(buffe)==0)
{
buffe[x+1] = '\0';
}
else if (c1=='\r' && strlen(buffe)>1)
{
printf ("%d", strlen(buffe));
printf ("\n%s", buffe);
hit = 1;
}
else{
}
}
strcpy(buffer, buffe);
return 1;
}
这段代码试图模仿scanf
可以看到的输入样式,然后按退格键删除先前输入的字符。我想“捕获”回车键,以便当用户按“Enter”键时,程序检查当前字符串(缓冲区)是否至少包含一个有效字符,并且当程序检查输入并发现用户按下按 Enter 键且字符串不包含任何内容,则循环继续。
我的代码的问题是,当我按 Enter 键时,程序启动后立即strlen
函数返回一个大于 0 的值,我认为这是不正常的,因为除了用户按下的“Enter”键之外,还没有用户输入。
对此有什么想法吗?
可能会尝试
char buffe[30] = {0};
(不过我还没有尝试过)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)