即使输入了正确的值 C 也会不断重复

do while keeps repeating even when entered the correct value C

我想开一个Y和N问答的节目。

#include <stdio.h> 
#include <stdlib.h>

int main(){
    char answer[256];
    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf("%s", answer);
    printf("%s", answer);
    }while(answer != "Y" || answer != "N")
;
    return 0;
}

如您所见,我声明了一个256个元素的char类型的变量,然后使用scanf记录了用户输入并将其存储在answer中。然后,只要用户输入大写的 Y 或 N,循环就会一直询问。问题是,使用此实现,即使我输入 Y 或 N,程序也会一直询问。我应该将 char 声明更改为单个字符吗?我已经试过了:

#include <stdio.h> 
#include <stdlib.h>

int main(){
    char answer;
    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf("%c", answer);
    printf("%c", answer);
    }while(answer != 'Y' || answer != 'N')
;
    return 0;
}

但我收到警告:

warning: format '%c' expects argument of type 'char *', but argument 2 has type int' [-Wformat=]
scanf("%c", answer);

有人对这个问题有说明吗?

此声明

Then the loop will be keeping asking as long the user enters either an uppercase Y or N.

意味着当用户输入 "Y" 或 "N" 时循环将停止迭代,不是吗?

这个条件可以这样写

strcmp( answer, "Y" ) == 0 || strcmp( answer, "N" ) == 0  

所以这个条件的否定(当循环将继续它的迭代时)看起来像

!( strcmp( answer, "Y" ) == 0 || strcmp( answer, "N" ) == 0 )

相当于

strcmp( answer, "Y" ) != 0 && strcmp( answer, "N" ) != 0  

请注意,您必须比较字符串(使用 C 字符串函数 strcmp),而不是指向它们第一个字符的指针,后者始终不相等。

所以第一个程序中do-while循环的条件应该是

    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf("%s", answer);
    printf("%s", answer);
    }while( strcmp( answer, "Y" ) != 0 && strcmp( answer, "N" ) != 0 )
;

那就是应该使用逻辑与运算符。

在第二个程序中你必须像这样调用 scanf

scanf( " %c", &answer);
       ^^^^   ^

和相同的逻辑AND运算符

    do {
    print("\nDo you want to delete yourself of the record?\n");
    scanf(" %c", &answer);
    printf("%c", answer);
    }while(answer != 'Y' && answer != 'N')
;