Count the number of lines, words, and characters within an input

Right now I'm browsing a book in C and come across an example in a book that I cannot get to work.

#include <stdio.h> #define IN 1 #define OUT 0 main() { 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); } 

It should count the number of lines, words, and characters inside the input. However, when I run it in the terminal, it does nothing. Am I missing something or is there a problem with this code?

+4
source share
6 answers

The program ends only when input is complete (getchar returns EOF). When working on the terminal, this usually never happens, and because of this it seems that the program is stuck. You need to close the entry manually by pressing Ctrl + D (possibly twice) in Linux or by pressing F6 and Enter at the beginning of the line in Windows (different tools can be used for different systems).

+8
source

He is waiting for input on stdin. Either redirect the file to it ( myprog < test.txt ), or enter the data and press Ctrl-D (* nix) or Ctrl-Z (Windows).

+3
source

When you run it, you need to enter the text, press return , then enter Ctrl-d and return (nothing more in the line) to mark the end of the file. It seems that I am working fine with my simple test.

+2
source

What he does is enter a loop for input. If you enter a character or a new line, nothing happens on the screen. You need to abort the process (on my Mac it is CTRL + D), which serves as EOF. Then you will get the result.

+2
source

getchar () returns the input from standard input. Start typing for which you want the number of words and the number of lines. Your entry stops when the EOF is reached, what you do by pressing CTRL D.

CTRL D in this case acts as a character to end the transfer.

amuses

+2
source

Usually I use this type of input (for Linux): 1. make a file (for example, with the name "input.txt"), enter your input and save 2. use the channel to send text to your application (here suppose your application with with the name "a.out" and in the current directory):

 cat input.txt | ./a.out 

You will see that the program is working correctly.

0
source

Source: https://habr.com/ru/post/1301236/