如果 else 循环以无法解释的方式工作

If else loop working in an unexplainable manner

我想创建一个 C 程序来创建字符数组的双向链表。输入将像在菜单中一样给出,具有添加元素、分离等的特定条件。最初我只接受字符输入 'V' 来创建列表,否则程序中断。

但是当我输入 'V' 作为输入(第一次)然后输入一个字符数组时,else 语句(在 while 循环内)也会被执行,这应该是不可能的。有人可以解释为什么会这样吗?它可能有一些我看不到的明显错误。

#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;
}

程序读取字符串后,输入缓冲区中仍有一个换行符。然后读取该换行符时,将输入 else 子句。解决方案是通过向格式字符串添加 space 来扫描第一个 non-whitespace 字符:

scanf(" %c", &x);

另见 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.