Reputation: 1417
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
Reputation: 16540
the following proposed code:
switch()
statement rather than a string of if()
statements (which means the integer is only evaluated once)double
literals rather than integer literalsand 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
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