hanugm
hanugm

Reputation: 1417

Program to count blanks, tabs, and newlines

I wrote the program as follows

#include<stdio.h>

int main() {

double nl=0,nb=0,nt=0;
int c;

while((c=getchar())!=EOF) {
        if(c == '\n') nl++;
        if(c == ' ') nb++;
        if(c == '\t') nt++;
}

printf("lines = %f, blanks= %f, tabs=%f ",nl,nb,nt);
return 0;

}

Input:

h   a i
i   am krishna

Output:

lines = 1.000000, blanks= 8.000000, tabs=0.000000 

In the input I gave two tabs(one in first line after h, and another in second line after i) and each tab contains 3 blank spaces in general. If we observe the output, it shows 1 new line(correct), 8 blanks(not correct, has to be 2) and 0 tabs (false, has to be 2).

Where it is going wrong? Why tab is counted as 3 spaces?

Upvotes: 0

Views: 884

Answers (2)

user3629249
user3629249

Reputation: 16540

the following proposed code:

  1. cleanly compiles
  2. uses a switch() statement rather than a string of if() statements (which means the integer is only evaluated once)
  3. properly uses double literals rather than integer literals
  4. follows the axiom: only one statement per line and (at most) one variable declaration per statement.

and now the code:

#include<stdio.h>

int main( void )
{

    double nl=0.0;
    double nb=0.0;
    double nt=0.0;
    int c;

    while((c=getchar())!=EOF)
    {
        switch(c)
        {
            case '\n':
               nl += 1.0;
               break;

            case ' ':
               nb += 1.0;
               break;

            case '\t':
               nt += 1.0;
               break;

            default:
               break;
        }
    }

    printf("lines = %f, blanks= %f, tabs=%f ",nl,nb,nt);
    return 0;
}

with the described input: (for illustrative purposes, <tab> actually is a tab character)

h<tab>a i
i<tab>am krishna

this is the output:

lines = 2.000000, blanks= 2.000000, tabs=2.000000 

Upvotes: 1

simo-r
simo-r

Reputation: 733

Your code works perfectly but the online compiler doesn't work properly because it uses spaces instead of tabs. Here is your code with little mods.

#include<stdio.h>

int main() {
/*Double has no sense*/
int nl=0,nb=0,nt=0;
int c;
while((c=getchar())!=EOF) {
        if(c == '\n') nl++;
        if(c == '\t') nt++;
        if(c == ' ') nb++;      
}

printf("lines = %d, blanks= %d, tabs=%d ",nl,nb,nt);
return 0;
}

Giving this input:

a   b c /*New line here*/
d   e f /*No new line*/

The output is correct:

lines = 1, blanks= 2, tabs=2

Upvotes: 2

Related Questions