jcm
jcm

Reputation: 205

Visual Studio (C) ignoring escape sequences

Going through Kernighan, and I am coding on visual studio with windows. Why doesn't the following program doesn't pick up tab characters, new lines, or spaces? I have to manually type its associated integer. Here's the word count program:

#define IN 1 /*State of being inside word*/
#define OUT 0 /*State of being outside word*/

countWords() {
    int c, nl, nw, nc, state;

    state = OUT;
    nl = (nw = (nc = 0));
    while ((c = getchar() != EOF)) {
        nc++;
        if (c == '\n') {
            nl++;
        }
        if (c == ' ' || c == '\n' || c == '\t') {
            state = OUT;
        }
        else if (state == OUT) {
            state = IN;
            nw++;
        }
        printf("%d %d %d\n", nl, nw, nc);
    }
}

My test input was 'one two three' and the output was '0 1 14'. Indicating that it didn't recognise space character ' '. Is there a setting on VS that needs to be changed to get this working?

Upvotes: 0

Views: 161

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134571

Be careful with operator precedence.

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

The c variable gets the boolean value of the expression getchar() != EOF. It doesn't hold the character that was read in like you are probably expecting.

You probably meant to write it as:

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

Upvotes: 3

Related Questions