Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

arrays - I'm stuck in a while loop in C

if((selected[0]=='H')&&(selected[1]=='Y')&&((selected[2]-'0')<=4))
{
    integer_v=10+(selected[1]*100)+(selected[2]-'0');
    printf("%d", integer_v);
}
else
{
    while((selected[0]!='H')||(selected[1]=='Y')||((selected[2]-'0')<=4))
    {
        printf("Wrong input!(%s) Please try again:
", selected);
        scanf(" %s", re_selected);
        strcpy(selected,re_selected);
    }
    integer_v=10+(selected[1]*100)+(selected[2]-'0');
    printf("%d", integer_v);
}

In my project to create this simple board game I cannot get out of this while loop. The purpose of this piece of code is to check if the input I gave(selected), which is a char array, has 'H' in first, 'Y' in second, and a digit from 1 to 4 in third slots of this array. But when I do it wrong once I get stuck in the while loop(The first try is successful). Even if the requirements are fullfilled the "Wrong input" message still appears. Example:

Choose which pawn you want to move:
HY5
Wrong input!(HY5) Please try again:
HY3
Wrong input!(HY3) Please try again:
HY4
Wrong input!(HY4) Please try again:

In here, HY5 is truly not the required input because 5>4 but HY4 is okay but the code still does not accept it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The condition of the while statement is wrong.

It is easy to simply add ! to negate the first condition for checking.

while(!((selected[0]=='H')&&(selected[1]=='Y')&&((selected[2]-'0')<=4)))

Another way is negating the condition using De Morgan's laws:

while((selected[0]!='H')||(selected[1]!='Y')||((selected[2]-'0')>4))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...