Search code examples
cscanf

Check for spaces from input stdin in C not working


Hy guys,

I just started to learn C and I'm having a problem, with my code. I'm trying to make a simple program which will take the input (name, password) and append it in a file.

int main()
{
    printf("1. Register\n");
    printf("2. Login\n");
    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]s\n", name);
        fprintf(file, "%s\n", name);

        printf("Enter password: ");

        //check if there's any spaces 
        fscanf(stdin, "%[^\n]s\n", password);
        fprintf(file, "%s\n", password);
    }

    return 0;
}

The problem is when I want to check if password or name contains any space. The compilation won't give me any error, but it will just print "enter username" and "enter password" and then will exit the program, if I don't use this check the program works accordingly.

the output when I try the check:

  1. Register
  2. Login

Please enter your choice: 1

Enter username: Enter password:

Can you please tell me what I'm doing wrong?


Solution

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

    You shouldn't malloc the sizeof an array you should rather use

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

    Also when you check that the malloc or file is NULL, if it fails you should return to stop the program.

    Also as @user3121023 said you should change "%[^\n]s\n" to " %[^\n]" with the added space at the start.