私は Linux を使用していますが、int
現在のキーの種類のASCII を返すカスタム関数があります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配列の代わりにポインターを使用しようとしましたが、2番目に文字を入力するとセグメンテーション違反が発生します。この関数は単独で動作しますが、ループ内では機能しません。少なくとも、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);