Thread: program to calculate number blanks, tabs and new lines in the input at command prompt

  1. #1
    Registered User
    Join Date
    Feb 2014
    Posts
    2

    program to calculate number blanks, tabs and new lines in the input at command prompt

    I am novice in c programming and have written the following program to calculate the number of blanks, tabs and new line characters in the input at the command prompt. I am using turbo c compiler and when i run this program i am getting correct output for number of tabs but for the other two the result is something which is very high and i can't understand. Please help.

    Code:
    #include<stdio.h>
    main()
    {
      int nb,nt,nl;
      int c;
      while((c=getchar())!=EOF)
      {
        if(c == ' ')
          nb++;
        if(c == '\t')
          nt++;
        if(c == '\n')
          nl++;
      }
      printf("blanks: %d\ntabs: %d\nnewlines: %d\n");
    }
    example run:
    input:
    this is the last
    time i am attempting to run
    this program before posting

    output:
    blanks:861
    tabs: 4
    newlines:230

    The output for tabs is as expected since i have given 4 tab characters but the remaining two values is a bit confusing.
    i have used ctrl+z to terminate the program if that makes any difference.

  2. #2
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    What are the values of nb, nt and nl before the while loop starts? (hint: claiming they start at 0 is wrong)

  3. #3
    Registered User
    Join Date
    Feb 2014
    Posts
    2
    thanks a lot, i have been trying to figure it out since this morning. this worked.

  4. #4
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    This mistake is probably one made by every programmer learning C. If you can, turn on higher warnings in your compiler (e.g. -Wall -Wextra), sometimes it can warn you about issues like these during the compile.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Entab - replacing blanks with tabs and blanks
    By thames in forum C Programming
    Replies: 3
    Last Post: 10-20-2012, 03:11 PM
  2. Replies: 1
    Last Post: 02-27-2012, 06:38 AM
  3. Replies: 2
    Last Post: 11-07-2010, 08:54 PM
  4. command prompt input, write into file
    By angela in forum C Programming
    Replies: 3
    Last Post: 03-17-2010, 09:00 AM
  5. How do you run a program from the command prompt?
    By 7stud in forum C++ Programming
    Replies: 5
    Last Post: 08-20-2003, 08:46 PM