我试图在Linux系统和GCC-4.7编译器上获取用于身份验证的用户名和密码,如下所示:
#include "stdio.h"
#include "stdlib.h"
#include <termios.h>
#include <unistd.h>
void getuserdata(char *passwd)
{
struct termios term, term_orig;
tcgetattr(STDIN_FILENO, &term);
term_orig = term;
term.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &term);
scanf("%s", passwd);
/* Remember to set back, or your commands won't echo! */
tcsetattr(STDIN_FILENO, TCSANOW, &term_orig);
}
int main()
{
char *password, *username;
printf("Enter username: ");
scanf("%s", username);
fflush(stdin);
printf("\n");
printf("\nEnter password: ");
getuserdata(password);
printf("Entered username is:%s\n", username);
printf("Entered password is:%s\n", password);
return 0;
}
预期行为如下:
Enter username: test
Enter password:
Entered username is: test
Entered password is: xxxx
但它不起作用,并以空作为用户名或密码。
伙计们,我做错什么了?
任何帮助都将不胜感激。
谢谢。
最佳答案
您没有为username
和password
分配内存。
char *password, *username;
username = malloc(50);
printf("Enter username: ");
scanf("%49s", username);
printf("\n");
printf("\nEnter password: ");
password = malloc(50);
getuserdata(password);
关于c - 来自scanf函数的输入给出了意外结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35145173/