【问题标题】:C K&R 1.5.4 Word Counting Exercise 1-9C K&R 1.5.4 字数练习 1-9
【发布时间】:2013-08-01 15:56:54
【问题描述】:

我想知道为什么下面的代码与下面的代码不完全一样。 代码应该做的是删除多个连续的空格并只显示一个空格:所以“它有效”变成了“它有效”。第一段代码只是让它像“它工作”一样。

没用

#include <stdio.h>

main(){
    int c;
    int lastspace;

    lastspace = 0;
    while((c = getchar()) != EOF){
        if(c != ' ')
            putchar(c);
            lastspace = 0;
        if(c == ' '){
            if(lastspace == 0){
            lastspace = 1;
            putchar(c);
            }
        }
    }
}

作品

#include <stdio.h>

main(){
    int c
    int lastspace;

    lastspace = 0;
    while((c = getchar()) != EOF){
        if(c != ' ')
            putchar(c);
        if(c == ' '){
            if(lastspace != c){
            lastspace = c;
            putchar(c);
            }
        }
    }
}

【问题讨论】:

  • isspace() 中还有一个函数&lt;type.h&gt;

标签: c word spaces counting


【解决方案1】:

在你的第一个例子中

if(c != ' ')
    putchar(c);
    lastspace = 0;

没有在if 语句之后放置{} 大括号,因此只有紧随其后的语句有条件地执行。改缩进加大括号说明代码其实是

if(c != ' ') {
    putchar(c);
}
lastspace = 0;

这就是为什么一些编码标准要求在所有控制语句之后使用{}

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多