即使输入正确的值C也会重复执行

问题描述 投票:0回答:1

我想开始一个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记录了用户输入并将其存储在答案中。然后,只要用户输入大写的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);

有人对此问题有澄清吗?

c do-while negation logical-or logical-and
1个回答
3
投票

此声明

然后,只要用户输入一个大写字母Y或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')
;
© www.soinside.com 2019 - 2024. All rights reserved.