If else loop working in an unexplainable manner

I want to create a C program to create a doubly linked list of character arrays. The input would be given like in a menu, with particular conditions for adding an element, breaking away etc. Initially I am only accepting the character input ‘V’ to create the list, otherwise the program breaks off.

But when I enter ‘V’ as the input (for the first time) and then a character array the else statement (inside the while loop) also gets executed which should be impossible. Can someone explain why this is happening? It may have some obvious mistake that I just cannot see.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>



struct website
{
    char web[30];
    struct website* forward;
    struct website* backward;
};


struct website* create(char* val, struct website* back) {
    struct website* curr = (struct website*)malloc(sizeof(struct website));
    if (curr) curr->forward = NULL;
    if (curr) curr->backward = back;
    if (curr) strcpy(curr->web, val);
    return curr;
}

int main() {

    struct website* websites = NULL;
    while (1) {

        char x;
        scanf("%c", &x);

        if (x == 'V') {

            char y[30];
            scanf("%29s", y);
            websites = create(y, websites);
        }
        else {
            printf("yes");
            break;
        }
    }
    printf(" bye ");
    return 0;
}

>Solution :

When the program has read the string there is still a newline character in the input buffer. When that newline character is then read the else clause is entered. The solution is to scan the first non-whitespace character by adding a space to the format string:

scanf(" %c", &x);

See also https://pubs.opengroup.org/onlinepubs/9699919799/

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.

Leave a Reply