【发布时间】:2014-03-14 00:51:32
【问题描述】:
我试图“捕获”用户的键盘输入,这意味着代码会阻止他们输入某些字符,在这种情况下会阻止输入数字和特殊字符。
#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”键。
对此有什么想法吗?
【问题讨论】:
-
如果您在开始时按 Enter,您似乎假设
strlen(buffe)将是0。但事实并非如此。局部变量不会自动初始化为 0,它们以垃圾内容开始。也许将char buffe[30];更改为char buffe[30]= { 0 };会有所帮助
标签: c