计算C中的选项卡,空白和换行符

时间:2018-01-25 04:37:48

标签: c

代码不起作用。 b(空白)和t(标签)的计数结果均为0.我认为可能存在我的条件设置问题。有人可以帮忙吗?

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);

}

2 个答案:

答案 0 :(得分:2)

您发布的代码相当于:

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);

}

您需要在while循环周围添加大括号,即

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;
}

另一件重要的事情:main()不是标准C
how does int main() and void main() work

答案 1 :(得分:0)

两个空格不是char,而是字符串。 试试this

if(c == ' ')
    b++;
if(c == '\t')
    t++;
if(c == '\n')
    nl++;