dj6450
dj6450

Reputation: 3

Do While loop always exits after first loop

I'm trying to make a small address book program in C where users would enter contact info which is stored in a text file. If a user opts to add a new contact, the program should ask them if they want to add another when they're finished. I've made an if statement which I believe should end the loop if they enter 'n' or continue for another contact if they write anything else. However if the user types 'y' (or anything else) it always exits after only 1 loop.

void new_contact(void){
    printf("Ready for new contact\n");
    int enter_new_contact = 1;
    char first_name[15];
    char second_name[20];
    char phone_number[12];
    char email[50];
    char y_n[1];
    do{
        printf("Enter the contacts first name.\n");
        scanf("%s", first_name);

        printf("Enter the contacts second name.\n");
        scanf("%s", second_name);

        printf("Enter the contacts phone number.\n");
        scanf("%s", phone_number);

        printf("Enter the contacts email.\n");
        scanf("%s", email);

        printf("%s\t%s\t%s\t%s\n", first_name, second_name, phone_number, email);

        printf("Would you like to add another contact?\n");
        scanf("%s", y_n);
        printf("%s\n", y_n);

        if(strcmp(y_n, "n")==0){
            enter_new_contact=0;
        }

    }while(enter_new_contact==1);
}

Thanks in advance!

Upvotes: 0

Views: 58

Answers (1)

Pras
Pras

Reputation: 4044

scanf("%s", y_n);

You have undefined behaviour here when scanf() tries to put '\0' in y_n, to which you allotted only one character. You should instead declare it as

char y_n[2];

and change the scanf statement to

scanf("%1s", y_n);

Upvotes: 4

Related Questions