Check for spaces from input stdin in C not working

Check for spaces from input stdin in C not working

Problem Description:

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. 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;

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 – 1

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]sn" to " %[^n]" with the added space at the start.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.