Adam Plšek
Adam Plšek

Reputation: 5

C : using getchar() in double while loop - stuck in loop?

Im using this double while loop. Im new to C.

int crawler;
char *desired[100];

crawler = getchar();

while(crawler != EOF) {

    int i = 0;

    while((crawler != '\n') && (crawler != EOF)) {
        desired[i] = crawler;
        i++;
        crawler = getchar();
    }

    printf("%s", desired);

}

I just dont see why Im getting infinite loop in here (LLLLLLLLL..). Stdin looks like this:

Lorem(newline)
Ipsum(newline)
Beach(newline)
Crocodile(newline)
Crox(newline)
C(EOF)

Any idea? thanks.

Upvotes: 0

Views: 316

Answers (1)

melpomene
melpomene

Reputation: 85767

Your outer loop ends when crawler is EOF.

Your inner loop ends when crawler is '\n' or EOF.

Only the inner loop reads input (by calling getchar).

Therefore: As soon as the first '\n' is read, the inner loop is never re-entered (the condition rejects '\n'), but the outer loop doesn't end, and it never changes the value of crawler.

Result: The outer loop spins without reading any input.

Upvotes: 3

Related Questions