【问题标题】:Counting Tab, Blank and Newlines in C [duplicate]C中的计数制表符,空白和换行符[重复]
【发布时间】:2018-01-25 04:37:47
【问题描述】:

代码不起作用。 b(blank) 和 t(tab) 的计数结果均为 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);

}

【问题讨论】:

  • 对循环使用大括号
  • 与 Python 不同,C 不关心缩进。只有第一个 if 语句在循环内。另外两个在循环之后,其中c 等于EOF
  • '\t' 用于tab(例如if (c == '\t') 不是多个空格。
  • 如果你使用 else if 它会起作用的!
  • 如果您使用调试器进行调试,或者只是添加了几个额外的 printfs,那么您将在没有 SO 的情况下解决此问题;(

标签: c


【解决方案1】:

您发布的代码相当于:

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

【讨论】:

    【解决方案2】:

    两个空格不是char,是string。 试试this

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

    【讨论】:

    • switch也可以考虑?
    • 出于可读性考虑,是的,但出于优化考虑,现代编译器也优化了这种“if”语句。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多