I have a piece of code here :
printf("Enter only parenthesis to arr or anything else to exit\n");
scanf(" %c", &data);
if (data != '(' || data != ')' || data != '[' ||
data != ']' || data != '{' || data != '}')
{
printf("\nExit scanning \n");
return;
}
My problem that no matter what i do when I enter any parenthesis it enters the "if" condition. I also tried getchar() but nothing worked either. Can you tell what's wrong I can't understand
CodePudding user response:
The problem is resolved simply.
First of all write the condition for which the input must satisfy
if (data == '(' || data == ')' || data == '[' ||
data == ']' || data == '{' || data == '}')
Now negate it
if ( !( data == '(' || data == ')' || data == '[' ||
data == ']' || data == '{' || data == '}' ) )
and open the parentheses and you will get
if (data != '(' && data != ')' && data != '[' &&
data != ']' && data != '{' && data != '}')
{
printf("\nExit scanning \n");
return;
}
That is all.
Another approach is to use standard string function strchr
declared in header <string.h>
as for example
if ( strchr( "()[]{}", data ) == NULL )
{
printf("\nExit scanning \n");
return;
}
Or if the user can enter the code 0 then
if ( data == '\0' || strchr( "()[]{}", data ) == NULL )
{
printf("\nExit scanning \n");
return;
}