1

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.

jestivus
  • 13
  • 3

3 Answers3

1

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()

Community
  • 1
  • 1
Erik Man
  • 824
  • 4
  • 17
0

The ENTER releases the buffer.

Up until the ENTER the data is not available to your code. Your code gets all the characters at the same time.

The operating system is in charge of maitaining the buffer (you might be able to change this aspect of your OS).

pmg
  • 106,608
  • 13
  • 126
  • 198
0

in c, any output (unless specifically set otherwise) is buffered.

Nothing is output until one of the following occurs:

  1. fflush() is called
  2. a '\n' is output
  3. the buffer is filled.

so you could add a call to flush() after the call to printf()

Note: there are other word separators that you should probably be looking for, other than tab, space, newline.

Suggest adding: single quotes, double quotes, period, colon, semicolon, left paren, left brace, right paren, right brace, back tick.

user3629249
  • 16,402
  • 1
  • 16
  • 17