0

This program here is supposed to count the number of occurrences blanks, tabs and newlines within the respective text you type within the program. However, after I compile the program and run it on ubuntu's terminal, all I am able to do is punch in text, space, enter etc... endlessly unless I hit ctrl z or c which ends the program.

I do not know how to get the program to execute the program's printf() function, bottom portion of the program, to print or show the calculations for the number of blanks, tabs and newlines. There are no compiler or linker errors, but perhaps it is a bug.

The last few lines of the program starting from "if(c == EOF)" excluding the printf() portion are also unclear to me.

#include <stdio.h>

int main(void)
{
  int blanks, tabs, newlines;
  int c;
  int done = 0;
  int lastchar = 0;

  blanks = 0;
  tabs = 0;
  newlines = 0;

  while(done == 0)
  {
    c = getchar();

    if(c == ' ')
      ++blanks;

    if(c == '\t')
      ++tabs;

    if(c == '\n')
      ++newlines;

    if(c == EOF)
    {
      if(lastchar != '\n')
      {
        ++newlines; /* this is a bit of a semantic stretch, but it copes
                     * with implementations where a text file might not
                     * end with a newline. Thanks to Jim Stad for pointing
                     * this out.
                     */
      }
      done = 1;
    }
    lastchar = c;
  }

  printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);
  return 0;
}

Edited by WaltP: Still can't figure out those pesky CODE Tags, eh?

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by mvmalderen
0

Please wrap your code in tags the next time.

Question:

I do not know how to get the program to execute the program's printf() function, bottom portion of the program, to print or show the calculations for the number of blanks, tabs and newlines. There are no compiler or linker errors, but perhaps it is a bug.

Answer:

If you're on Windows, the Ctrl+Z key combination sill signal end-of-file and cause getchar to return the EOF flag rather than extract a character from the stream. On Unix/Linux, the key combination is Ctrl+D.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.