检查C中输入stdin中的空格是否不工作



大家好,

我刚开始学习C语言,我的代码有问题。我正试图使一个简单的程序,将采取输入(名称,密码),并将其附加在一个文件。

int main()
{
printf("1. Registern");
printf("2. Loginn");
printf("Please enter your choice: ");
int choice;
FILE *file = fopen("data.txt", "a");
if (file == NULL)
printf("File cannot be oppened");
char *name = (char *)malloc(sizeof(char[64]));
if (name == NULL)
printf("name malloc failed");
char *password = (char *)malloc(64 * sizeof(char));
if (password == NULL)
printf("password malloc failed");
char *userInput = (char *)malloc(1024 * sizeof *userInput);
if (userInput == NULL)
printf("userInput malloc failed");
scanf("%d", &choice);
if (choice == 1)
{
printf("Enter username: ");
fscanf(stdin, "%[^n]sn", name);
fprintf(file, "%sn", name);
printf("Enter password: ");
//check if there's any spaces 
fscanf(stdin, "%[^n]sn", password);
fprintf(file, "%sn", password);
}
return 0;
}

问题是当我想检查密码或名称是否包含任何空格时。编译不会给我任何错误,但它会打印"enter username"并"输入密码"然后将退出程序,如果我不使用此检查,程序将相应地工作。

检查时的输出:

  1. 登录

请输入您的选择:1

输入用户名:输入密码:

你能告诉我我做错了什么吗?

char *name = (char *)malloc(sizeof(char[64]));

你不应该malloc数组的大小,你应该使用

char *name = (char *)malloc(sizeof(char) * 64);

当您检查malloc或文件是否为NULL时,如果失败,您应该返回以停止程序。

也如@user3121023所说,你应该将"%[^n]sn"更改为" %[^n]",并在开始处添加空间。

最新更新