Questioneer
Questioneer

Reputation: 793

Do I have a logic issue?

contact entry = {"", "", "", ""};

while (choice == 1 || 2 || 3 || 4){  
    if (choice == 1){
        printf ("First name: \n");    
        fgets(entry.firstname, sizeof(entry.firstname),stdin); 
        break;
    }
    else if(choice == 2){
        printf ("Last name: \n");     
        fgets(entry.lastname, sizeof(entry.lastname),stdin); 
        break;
    }
    else if(choice == 3){
        printf ("Address: \n");   
        fgets(entry.address, sizeof(entry.address),stdin); 
        break;
    }
    else if (choice == 4){
        printf ("Phone number: \n");      
        fgets(entry.phone, sizeof(entry.phone),stdin); 
        break;
    }
    else{
        printf("Exiting");
        return 0;
    }
}

fwrite (&entry, sizeof (contact), 1, pFile);
fclose(pFile);

This is the code I have. It seems simple enough and I've traced it following it if I press 1,2,3, or 4 . So it knows which if ,else if, else body to go to but it seems to exit really quickly as well as not write what I want it to to the file. Any obvious mistakes here? Thanks in advance.

EDIT 1:

I changed while (choice >= 1 && choice <= 4){ to while (choice >= 1 && choice <= 4){ , but I still have an issue with nothing being written to the file. pFile = fopen("C:\contacts.txt", "w+"); is the correct way to do this by my understanding.

Upvotes: 1

Views: 82

Answers (4)

lorean
lorean

Reputation: 2150

while (choice == 1 || 2 || 3 || 4)

Is the same as saying

while (choice == 1 || TRUE == 2 || TRUE == 3 || TRUE == 4)

Upvotes: 1

Roman Byshko
Roman Byshko

Reputation: 9032

You have syntax mistakes

choice == 1 || 2 || 3 || 4

should be

choice == 1 || choice ==  2 || choice ==  3 || choice == 4

Upvotes: 1

stacker
stacker

Reputation: 68972

The expression choice == 1 || 2 || 3 || 4 will always evaluate to true

choice == 1 evaluates to 1 if choice is 1 (true) otherwise to 0 (false) 2,3 and 4 evaluate to true if you do a logical or (||) it will result in

false || true || true || true -> true

what you mean is probably

choice >= 1 && choice <= 4

Upvotes: 4

Paul R
Paul R

Reputation: 213059

Change:

while (choice == 1 || 2 || 3 || 4){  

to:

while (choice == 1 || choice == 2 || choice == 3 || choice == 4){  

or perhaps more succinctly:

while (choice >= 1 && choice <= 4){  

Upvotes: 5

Related Questions