tags:

views:

160

answers:

6
+3  Q: 

Newbie C Problem

Right now I am going through a book on C and have come across an example in the book which 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);
}

Its supposed to count the number of lines, words, and characters within an input. However, when I run it in the terminal it appears to do nothing. Am I missing something or is there a problem with this code?

+3  A: 

When you run it, you need to type in your text, press return, then type Ctrl-d and return (nothing else on the line) to signify end-of-file. Seems to work fine with my simple test.

Ramashalanka
+2  A: 

What it is doing is entering a loop for input. If you enter a character or newline, nothing happens on the screen. You need to interrupt the process (on my Mac this is CTRL+D) which serves as EOF. Then, you will get the result.

Ryan Rosario
Ah, I didn't realize that I would need to manually stop the loop with an end of file. Thanks for the quick response.
Protean
You should wait a little longer before marking a question as the best. Just a thought...
Ryan Rosario
+7  A: 

The program only terminates when the input ends (getchar returns EOF). When running on terminal, this normally never happens and because of this it seems that the program is stuck. You need to close the input manually by pressing Ctrl+D (possibly twice) on Linux or pressing F6 and Enter at the beginning of the line on Windows (different systems may use different means for this).

Tronic
Never used F6 for this on Windows though I have no doubt you are right, Ctrl-Z works on Windows and MS-DOS FYI, for arcane historical CP/M compatibility reasons it is used as the EOF character on MS-DOS and inherited by Windows.
Clifford
+3  A: 

It's waiting for input on stdin. Either redirect a file into it (myprog < test.txt) or type out the data and hit Ctrl-D (*nix) or Ctrl-Z (Windows).

Ignacio Vazquez-Abrams
+2  A: 

Hi

getchar() returns the input from the standard input. Start typing the text for which you want to have the word count and line count. Your input terminates when EOF is reached, which you do by hitting CTRL D.

CTRL D in this case acts as an End Of Transmission character.

cheers

Andriyev
A: 

I usually handle this kind of input like this (for Linux): 1. make a file (for example, named "input.txt"), type your input and save 2. use a pipe to send the text to your application (here assume your application named "a.out" and in the current directory):

cat input.txt | ./a.out

you'll see the program running correctly.

Daybreakcx