jestivus jestivus - 27 days ago 9
C Question

C: Why does the "Enter" key trigger output in this code?

Here's my code for exercise 1-13 in "The C Programming Language":

#include <stdio.h>

int main()
{
int c, currentIndex, currentLength;

currentLength = currentIndex = 0;

while ((c = getchar()) != EOF){
if (c == '\t' || c == '\n' || c == ' '){
if (currentLength == 0){
continue;
}

printf("Length of word %d: ||", currentIndex);

for (int i = 0; i < currentLength; i++){
putchar('-');
}
putchar('\n');

currentLength = 0;
++currentIndex;
} else {
++currentLength;
}
}

return 0;
}


So I can compile this and run it with ./a.out, but when I press "Enter" to start a new line of input ('\n') it runs the printf() and putchar() functions(and neither ' ' or '\t' trigger the output). The while loop doesn't end (it ends as it should with END-OF-FILE(CTRL-D)) but I'm wondering why these functions are being called when they are. It prevents input of multiple lines at a time. Here's an example of it's output:

how long are these words
Length of word 0: ||---
Length of word 1: ||----
Length of word 2: ||---
Length of word 3: ||-----
Length of word 4: ||-----


Just to be clear, I ONLY get the output from printf() and putchar() when I press "Enter". CTRL-D just ends the loop and the program.

Answer

getchar() by default is in buffered mode, so the characters are not given to your program until enter is pressed. Duplicate of this question: How to avoid press enter with any getchar()

Comments