我使用的是 Linux,有一个自定义函数返回当前 key 的 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’
我尝试使用指针而不是 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);
最佳答案
问题是 strcat
需要一个 char *
作为它的第二个参数(它连接两个字符串)。您没有两个字符串,您有一个字符串和一个 char
。
如果你想在pass
的末尾添加c
,只需要保留一个int i
来存储的当前大小pass
然后做类似的事情
pass[i] = (char) c
。
确保在完成时以 null 终止 pass
(通过将最后一个位置设置为 0)。
关于c - Strcat 在类似 getch 的简单密码输入上抛出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4093847/