Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character constant too long for its type (fgets)

Tags:

arrays

c

void verification() {
    char pass[50];

    printf(" Enter Password : ");
    fgets(pass, 50, stdin);

    if (pass != 'aaanc6400') {   \\ Warning message in here
        printf("\n Invalid Password.. Please enter the correct password. \n\n");
        verification();
    }
    info();
}

When I compile the program, on the marked line it shows warning that "Character constant too long for its type" and also "Comparison between pointer and integer". And then when I run the code and enter the correct password, it still prints that the password is wrong. What am I doing wrong?

like image 549
Anik Shahriar Avatar asked Jan 17 '26 15:01

Anik Shahriar


2 Answers

The warning is about you declaring that you have a character of a big length.

'aaanc6400'

is a 9 character long character and the compiler warns you, that it might be a typographical error. It's right.

In C, we use single quote ' for characters and " double quotes for strings which are arrays of characters terminated with '\0' character.

So you have to replace 'aaanc6400' with "aaanc6400" and use strcmp. Remember! fgets might read the \n also, so you can compare the input with "aaanc6400" and "aaanc6400\n" as well. This solution would be sufficient for student project.

like image 65
xenteros Avatar answered Jan 20 '26 06:01

xenteros


You need to:

  • Initialise char pass[50] = "";
  • Remove \n from fgets by pass[strlen(pass) - 1] = '\0'; (after fgets) - that helps you to compare string later on.
  • if (pass != 'aaanc6400') this one is totally wrong. Use strcmp for string comparison, and double quote for string "aaanc6400"

From @chux: It's better to use strcspn instead of strlen to trim off the \n from fgets

    char pass[50] = "";
    printf(" Enter Password : ");
    if(fgets(pass, 50, stdin) == NULL)
    {
        perror("fgets error");
        return;
    }
    pass[strcspn(pass, "\n")] = 0;  // trim \n

    if(strcmp(pass, "aaanc6400")) {
        printf("\n Invalid Password.. Please enter the correct password. \n\n");
        verification();
    }
like image 37
artm Avatar answered Jan 20 '26 05:01

artm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!