c - Strcat 在类似 getch 的简单密码输入上抛出段错误

标签 c console user-input getch

我使用的是 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/

相关文章:

c - 分配给字符串数组的内存量?

c - C 中的 OpenGL 对象加载器

C 程序通过多次调用 realloc() 崩溃

debugging - 如何在GDB中跳转到断点?

c++ - fprintf()/std::cout 不会将字符串的一部分打印到 stdout/stderr

php - 如何在复选框组上使用filter_input?

c# - winforms 应用程序如何在没有焦点的情况下接受用户输入?

c - Sprintf 连接字符串

c# - 是否可以拦截控制台输出?

c++ - cin.getline() 奇怪的行为