Unable to detect logical error in program C

A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program correctly prints the result, one word per line. After a corresponding change in the condition, I expected the program below to also print one word per line. However, I am not getting the correct result. Am I making some kind of stupid mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
+5
source share
8 answers

correct change of condition:

if (!(c == ' ' || c == '\n' || c == '\t'))

or

if (c != ' ' && c != '\n' && c != '\t')

See De Morgan Law

+16
source

, : , , . -, (, , ), , .

isspace , (, , ). -, , , - .

, scanf %s:

char buffer[256];

while (scanf("%255s", buffer))
    printf("%s\n", buffer);

, , . , /.

+4

|| && s, ..

        if (c != ' ' || c != '\n' || c != '\t')

        if (c != ' ' && c != '\n' && c != '\t')

. "IF c AND c, AND c, THEN..."

+3

:

!(A || B) == (!A && !B)
!(A && B) == (!A || !B)

: :

if ( c != ' ' && c != '\n' && c != '\t' )
+2

, MByD, (||) (& &).

+1

.

!(c== ' ' || c== '\n' ||c == '\t')

:

c!= ' ' && c!= '\n' &&c != '\t'

.

:

(A & B) , (! A ||! B)

0

A or B or C not A and not B and not C, :

if(c != ' ' && c != '\n' && c != '\t')
0

You need to get a little bit involved in DeMorgan Laws . It is not enough to change the combination operators from "||" "& &", you must also negate all the elements that combine to get the same set of solutions.

0
source

All Articles