我使用的是Linux,有一个自定义函数返回一个ASCII
int
当前键的类型
getch()
. 当我试图习惯它以及如何存储我遇到问题的密码时,我的代码如下:
int main() {
int c;
char pass[20] = "";
printf("Enter password: ");
while(c != (int)'\n') {
c = mygetch();
strcat(pass, (char)c);
printf("*");
}
printf("\nPass: %s\n", pass);
return 0;
}
不幸的是,我得到了GCC的警告:
pass.c:26: warning: passing argument 2 of âstrcatâ makes pointer from integer without a cast
/usr/include/string.h:136: note: expected âconst char * __restrict__â but argument is of type âcharâ
我尝试使用指针而不是字符数组来传递,但第二次我键入一个字母它会出错。函数本身工作,但不在循环中工作,至少与Windows系统上的getch()不同。
你能看到我的例子有什么问题吗?我很喜欢学习这个。
编辑:
多亏了这些答案,我想出了以下愚蠢的代码:
int c;
int i = 0;
char pass[PASS_SIZE] = "";
printf("Enter password: ");
while(c != LINEFEED && strlen(pass) != (PASS_SIZE - 1)) {
c = mygetch();
if(c == BACKSPACE) {
//ensure cannot backspace past prompt
if(i != 0) {
//simulate backspace by replacing with space
printf("\b \b");
//get rid of last character
pass[i-1] = 0; i--;
}
} else {
//passed a character
pass[i] = (char)c; i++;
printf("*");
}
}
pass[i] = '\0';
printf("\nPass: %s\n", pass);