0

The code won't work. The counting results of b(blank) and t(tab) are both 0. I think there maybe the issue with my condition set up. Can anyone help?

main()
{
int c, b, t, nl;

nl = 0;
b = 0;
t = 0;
    while ((c = getchar()) != EOF)
        if (c == '\n')
            ++nl;
        if (c == ' ')
            ++b;
        if (c == '  ')
            ++t;

    printf("%d\t%d\t%d\n", nl, b, t);

}
Bill Cao
  • 1
  • 1

2 Answers2

2

The code as posted by you is equivalent to:

main()
{
int c, b, t, nl;

nl = 0;
b = 0;
t = 0;
    while ((c = getchar()) != EOF) //your code is equivalent to this
    {
        if (c == '\n')
            ++nl;
    } //the following if conditions fall outside the loop
        if (c == ' ')
            ++b;
        if (c == '\t')//tab is represented by \t not by '  '
            ++t;

    printf("%d\t%d\t%d\n", nl, b, t);

}

You need to add braces around your while loop i.e.

int main(void)
{
int c, b, t, nl;

nl = 0;
b = 0;
t = 0;
    while ((c = getchar()) != EOF){
        if (c == '\n')
            ++nl;
        if (c == ' ')
            ++b;
        if (c == '\t')
            ++t;
        }
    printf("%d\t%d\t%d\n", nl, b, t);
    return 0;
}

Another important thing: main() is not standard C
how does int main() and void main() work

Aditi Rawat
  • 784
  • 1
  • 12
  • 15
0

Two spaces is not char, it is string. Try this:

if(c == ' ')
    b++;
if(c == '\t')
    t++;
if(c == '\n')
    nl++;
Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34