0

I try to check how many @ there are in the string which I input. The problem is that I printf “c” once I “int c=0”, but “c” is a random integer in the output. How can I check if there is only one @ in the email address that I input?

typedef struct The_users {
    char id[20]; 
    char pwd[20];
    char name[20];
    char email[20];
} users;

//register system
void registers() {
    users a, b;
    FILE* fp;
    char temp[20];
    int count = 0;

    if (fp = fopen("users.txt", "r") == NULL) {
        fp = fopen("users.txt", "w");
        fclose(fp);
    }

    fp = fopen("users.txt", "r");

    fread(&b, sizeof(struct The_users), 1, fp); 

    while (1) {
        printf("Please enter your email:\n");
        gets(a.email);
        int c = 0;
        for (int i = 0; i < 20; i++) {
            if (a.email[i] == "@") {
                c++;
            }
        }
        if (c == 1) {
            break;
        } else {
            printf("----------------------------------------------\n");
            printf("Not a correct email address! Please try again!\n");
            printf("----------------------------------------------\n");
        }
    }
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117

1 Answers1

2

There are multiple errors in the code:

  • missing parentheses in if (fp = fopen("users.txt", "r") == NULL): fp receives the result of comparing the return value of fopen with NULL. You want this instead:

     if ((fp = fopen("users.txt", "r")) == NULL)
    
  • does you file really have a format compatible with the read call fread(&b, sizeof(struct The_users), 1, fp);? It is more common to store the info as text on separate lines.

  • you loop to check for the presence of @ in the email array inside the structure should work although you should probably stop at the null terminator and make this array longer. You might then simply write:

      c = strchr(a.email, '@') != NULL;
    

Note however that more checks might be worthwhile to reject invalid emails: the @ should not come first, nor last, and there should be a single @. Both the address and the domain name have further constraints.

chqrlie
  • 131,814
  • 10
  • 121
  • 189