Reputation: 41
I'm having an error with the following code. It's relatively simple but I can't figure out where I'm going wrong. Here's a part of the code:
int target=0,nextRow;
char nextCol;
while(target == 0)
{
printf("Enter a valid target: ");
scanf("%c%d",&nextCol,&nextRow);
if(nextCol>= 'a' && nextCol <= 'z') /* convert to uppercase */
nextCol=nextCol-32;
if(nextRow>row || nextRow<1 || nextCol<'A' || (nextCol-64)>col)
target=0;
else
target=1;
}
Essentially the user is prompted to input a char and int e.g. B4, C8 etc. Col and Row are predefined integers. If the user-input values are out of bounds target remains as 0. Else target=1 so the loop will exit. When I run this and keep inputing invalid values, "Enter a valid target" starts repeating. Why?
Upvotes: 0
Views: 41
Reputation: 15032
Apparently, the condition (nextCol-64)>col
seems to be misplaced.
If you input f.e. 'b'
as input for nextCol
, the expression would be evaluated to 2 > col
which seems to be wrong.
Also I consider that col
and maybe even row
have the value of 0
in which case, the corresponding conditions would always evaluate to true
and the loop will never terminate as it seems to do.
Overthink the logic of your program!
Upvotes: 1