Why the below condition:
if (c !=' ' && c !='\t' && c !='\n')
matches either:
not space not \n - when input is "abc \n"
or
not \t not \n - when input is "abc\t\n"
When AND logical operator is used? Should not AND require to match all conditions the same time?
Not space NOT \t NOT \n
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
int main() {
int c, state;
state = OUT;
while ((c = getchar()) != EOF) {
if (c !=' ' && c !='\t' && c !='\n')
{
printf("%c", c);
state = IN;
}
else if (state)
{
printf("\n");
state = OUT;
}
}
}
CodePudding user response:
You seem to be confused regarding what the condition is actually checking for.
This condition:
if (c !=' ' && c !='\t' && c !='\n')
Written out as English, says: "if c
is not a space AND c
is not a tab AND c
is not a newline".
In other words, the condition is true when c
matches none of those 3 characters.
CodePudding user response:
It is working as intended, test it with vertical-tab.
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
int main() {
int c, state;
state = OUT;
while ( (c = getchar()) != EOF) {
if (c != ' ' && c != '\t' && c != '\n') {
printf ("%c", c);
state = IN;
} else if (state) {
printf ("\v");
state = OUT;
}
}
return 0;
}
space
, newline
& tab
chars are ignored and after every word we print a vertical-tab
. We see this step pattern to prove that.
There are tab
s in 2nd edition
./a.out
C Programming Language 2nd edition exercise 1-12 question
C
Programming
Language
2nd
edition
exercise
1-12
question