c++ validate range of characters [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm writing a function that is passed a character as the first argument and an integer as the second. I need to validate both simultaneously. Specifically, the character must be between A and J (including A and J), and the integer must be between 1 and 10 (including 1 and 10).
The line I wrote is:
if (toupper(row) < 'A' || toupper(row) > 'J' || col < 1 || col > 10)
{
return 0;
}
else
{ ... rest of function ... }
but this is not working correctly. In my book I read that you could perform comparisons with characters because they really are just integers themselves, but I can't figure out why ths won't work. Could anyone point me in the right direction?
Edit to address some comments
0 is the number we're supposed to return if the input is not valid.
This line of code is part of a project that is being graded by a "test driver" that my teacher wrote. The test driver is reporting that my function is not returning the correct result when the input is invalid (character that is not between A or J, or a number that is lower than 1 or greater than 10).
I structured my code so that if the statement above is true, then it returns the code we were supposed to return, otherwise it proceeds with the rest of the function... So I can't figure out why his test driver is telling me that I'm not returning the code when given invalid input. The other problem is he doesn't let us see what the test driver is sending to our function, so I have no way of trouble shooting this.

I think that you shouldn't use toupper. Why?
Because maybe your professor use invalid input like:
a, 5
and you shouldn't allow lower cases to pass your test.
So in the end your if statement:
if ((row >= 'A' && row <= 'J') && (col > 0 && col < 11))

From your post it is not clear what does not work. You wrote if statement without any compound statement. So what is the criterion that something is wrong?!
For example you could write
if (toupper(row) < 'A' || toupper(row) > 'J' || col < 1 || col > 10) return false;
Take into account that negation of expression
if ((toupper(row) >= 'A' && toupper(row) <= 'J') && (col > 0 && col < 11) )
as it is written by #Ardel is equivalent to
if ( !( ( toupper(row) >= 'A' && toupper(row) <= 'J') && (col > 0 && col < 11 ) ) )
that in turn is equivalent to
if ( !( toupper(row) >= 'A' && toupper(row) <= 'J') || !(col > 0 && col < 11 ) ) )
that is equivalent to
if ( !( toupper(row) >= 'A' ) || !( toupper(row) <= 'J') || !(col > 0 ) || !( col < 11 ) )
that is equivalent to
if ( toupper(row) < 'A' || toupper(row) > 'J' || col <= 0 ) || col >= 11 )
that is at last equivalent to
if (toupper(row) < 'A' || toupper(row) > 'J' || col < 1 || col > 10) return false;
That is your original expression.
So there is no any sense in your post and in the answer of #Ardel.
So I do not understand for example why the answer of #Ardel was uo voted. Maybe it was up voted by whose who is unable to do such conversions as the negation of boolean expressions?:)
I can suppose (moreover after thinking about I am sure) that you should not apply function toupper to the character. For example
if ( row < 'A' || row > 'J' || col < 1 || col > 10) return 0;
The other problem is that you did not say what the function shall do if this condition will be passed successfuly. Maybe inside the function body you should reassign row the following way
row -= 'A';
that to use it as integer value between 1 and 10 inclusively.

Related

Avoiding incrementing in if statement in C++

I would like to avoid incrementing and decrementing in if-statement since there is a segmentation fault error in the following code while checking conditions (if we start with p = 1 and k = 1 for example):
if (((heights[k--][p--] < heights[k][p]) || (heights[k--][p--] == heights[k][p])) &&
((heights[k--][p++] < heights[k][p]) || (heights[k--][p++] == heights[k][p])) &&
((heights[k++][p--] < heights[k][p]) || (heights[k++][p--] == heights[k][p])) &&
((heights[k++][p++] < heights[k][p]) || (heights[k++][p++] == heights[k][p]))){
width[k][p] = 3;
}
For example, the second check fails with k = -1.
I would like to check neighbouring elements of a two-dimensional array heights in an if-statement and than run some logic in case it was true.
How can I optimise it and generally rewrite it to make it look (and work) better? I haven't found any information on it.
As others have indicated, replacing 'k--' with 'k-1' and 'k++' with 'k+1' for all 'k' and 'p' variables may resolve the segmentation error. 'k+1' is a reference to the next array index after 'k', while 'k++' increments the value of 'k' after it's used. It's also good programming practice to avoid using expressions as arguments.
https://en.cppreference.com/w/cpp/language/operator_incdec
To clean up the code, you could also simplify the logical OR by replacing '<' with '<='.
if ((heights[k-1][p-1] <= heights[k][p]) &&
(heights[k-1][p+1] <= heights[k][p]) &&
(heights[k+1][p-1] <= heights[k][p]) &&
(heights[k+1][p+1] <= heights[k][p])){
width[k][p] = 3;
}

How a single variable with two relational operators works internally [duplicate]

This question already has answers here:
Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?
(5 answers)
Closed 4 years ago.
We usually use logical operators if need to combine boolean expressions. I was wondering about the expressions if don't use logical operators.
int x=101;
if(90<=x<=100)
cout<<'A';
This code still prints 'A' on console. Can you please help me to understand that how and in which order this boolean expression would be evaluated.
Since the operators have equal precedence, the expression is evaluated left-to-right :
if( (90 <= x) <= 100 )
if( (90 <= 101) <= 100 ) // substitute x's value
if( true <= 100 ) // evaluate the first <= operator
if( 1 <= 100 ) // implicit integer promotion for true to int
if( true ) // evaluate the second <= operator
To achieve the comparison you want, you would use the condition :
if( 90 <= x && x <= 100)
This is a common source of errors, because it looks right, and sytactically it is correct.
int x=101;
if(90<=x<=100)
This is equivalent to
if ( (90 <= x) <= 100)
which is
if ( true <= 100 )
and as true can convert to 1 this is
if ( true )
This expression is roughly equals to
int x=101;
bool b1 = 90 <= x; // true
bool b2 = int(b1) <= 100; // 1 <= 100 // true
if(b2)
cout<<'A';
So here is true result.

How to remove empty (or filled with incorrect data) fields

As I have read, the C++ compiler initialize table with the random data, before I initialize it by myself.
I've got a program which after performing (for example) give me this output - char table.
{'D','K','2','EMPTY FIELD','1','+','EMPTY FIELD','EMPTY FIELD','3','EMPTY FIELD','/'}
Now I would like to delete whole inconvenient data like letters, and empty fields.
I'm trying to achieve this by this code, but I think it transfer it into ASCII code. Am I able to achieve this in another way ?
char wynik[20];
int j = 0;
for (int i = 0; i <20; i++)
{
if (wyjscie[i] == '+' || wyjscie[i] == '-' || wyjscie[i] == '/' || wyjscie[i] == '*' || (wyjscie[i] >-241241 || wyjscie[i] < 2141242142 ))
{
wynik[j] = wyjscie[i];
j++;
}
}
(wyjscie[i] >-241241 || wyjscie[i] < 2141242142 ) is your problem. You're confusing the integer values represented by a character and the integer codes of characters. If you want to check if a character c is between 0 and 9 you could do c >= '0' && c <= '9'.

Make assignment within if-statement

I have the following problem
in my app i have severeal if-statements
if ( (number >= 1 && number <= 18) && !strcmp("half1-18", _myBetCh) ) {
}
Now I realized that I have to split this condition because I need a boolean variable after one condition
bool success = false,
if(!strcmp("half1-18", _myBetCh) {
success = true;
if (number >= 1 && number <= 18) {
}
}
Is there a workaround to this? Is it possible, for instance, to make an assignment withing the if-statement?
It's possible, like this:
if ((success = !strcmp("half1-18", _myBatCh)) && number > 1 && number < 18)
but I personally think assignments in conditions are messy and hard to read, and prefer this variation:
bool success = strcmp("half1-18", _myBetCh) == 0;
if (success && number >= 1 && number <= 18) {
// ...
}
Well, there is:
if ( !strcmp("half1-18", _myBatCh) && (success = true, number > 1 && number < 18) )
or, obviating the need for the success = false earlier
if ( (success = !strcmp("half1-18", _myBatCh)) && number > 1 && number < 18 )
Your way is easier to read though, so I would consider sticking with what you've got.

C vs. Python - operator precedence in conditional statements [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How does the C process a conditional statement such as n >= 1 <= 10?
I initially thought that it would get evaluated as n >= 1 && 1 <= 10, as it would be evaluated in Python. Since 1 <= 10 is always true, the second porition of the and is redundant (the boolean value of X && True is equivalent to the boolean value of X).
However, when I run it with n=0, the conditional gets evaluated to true. In fact, the conditional always seems to evaluate to true.
This was the example I was looking at:
if (n >= 1 <= 10)
printf("n is between 1 and 10\n");
>= operator is evaluated from left to right, so it is equal to:
if( ( n >= 1 ) <= 10)
printf("n is between 1 and 10\n");
The first ( n >= 1 ) is evaluated either as true or false, which is equal to either 1 or 0. Then that result of 1 or 0 is compared to result <= 10 which will always evaluate to true.
Thus the statement printf("n is between 1 and 10\n"); will always be printed
It's evaluated left to right like this:
n = 5;
if (n >= 1 <= 10)
// then
if (1 <= 10)
// then
if (1)
It first checks if n >= 1. If it is, it evaluates to 1, otherwise 0. This leads to the next evaluation, 1 <= 10, which evaluates to 1 as well. Note that this also succedes:
n = 5;
if (n >= 3 == 1)
Because it's evaluated like this:
n = 5;
if (n >= 3 == 1) // but you should never write code like this
// then
if (1 == 1)
// then
if (1)
Also note why it works with n = 0
n = 0;
if (n >= 1 <= 10)
// then
if (0 <= 10) // 0 isn't greater or equal to 1, so 0 (false) is "returned"
// then
if (1) // but 0 is less than or equal to 10, so it evaluates as 1 (true)