c - K&R Exercise 1-9 : output the input, 用一个空格替换多个空格

标签 c kernighan-and-ritchie

我一直在研究一些关于 C 的书籍,试图让我的 C 腿(海腿!明白了吗?!)。我刚刚完成了 K&R 书中的练习 1-9,作为引用,它是“编写一个程序将其输入复制到输出,用一个空格替换一个或多个空格的每个字符串”。不过,我对我的代码发生了什么有疑问——

#include <stdio.h>

//Copy input to output. Replace each string of multiple spaces with one single space

int main(int argc, char *argv[]){

    int ch, lch;      // Variables to hold the current and last characters, respectively


    /* This loop should 'put' the current char, then store the current char in lc,
     * loop back, 'get' a new char and check if current and previous chars are both spaces.
     * If both are spaces, do nothing. Otherwise, 'put' the current char
     */

    for(ch = getchar(); (ch = getchar()) != EOF; lch = ch){
            if(ch == ' ' && lch == ' ')
                    ;
            else putchar(ch);
    }

    return 0;
}

除了第一个字符输入外,这大部分都有效。例如,如果第一行输入是

"This        is   a test"

我的代码输出

"his is a test". 

在放弃第一个字符输入后,程序会始终如一地工作以满足练习的要求。

有人可以告诉我我在循环中犯的错误导致了这个问题吗?也欢迎任何其他建议。

最佳答案

在 for 循环语句中,您遇到了错误。

for(ch = getchar(); (ch = getchar()) != EOF; lch = ch){...}

在这里,您将第一个字符存储在 ch 中,然后通过再次读取字符输入再次测试 if (ch!=EOF)。

从初始化语句中删除ch=getchar();让它在第二部分。

for(;(ch = getchar()) != EOF; lch = ch){...}

此外,您必须在运行 lch 之前对其进行初始化,因为在循环的第一次迭代中进行比较之前,lch 中不会存储任何值。所以,让lch=0先被初始化。

for(lch = 0; (ch = getchar()) != EOF; lch = ch){...}

考虑在您的编译器中启用警告,它可能会检测并警告此问题,因此您可以修复它。

以上内容可以解决您的问题。

(感谢蓝月亮和hyde帮我修改答案。)

关于c - K&R Exercise 1-9 : output the input, 用一个空格替换多个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31597961/

相关文章:

c - 使用写时复制分配内存

java - 使用C/C++/Java获取基本硬件信息

c - K&R 中发现的 C 问题中的二叉树实现

c++ - 运行时库只是一些动态链接的库文件吗?

c - 将字符串数组传入函数+此数组的动态分配不起作用

C-K&R 表达式 : evaluate a reverse Polish expression from the command line

c - 解释一下我的 C 代码的结果。 K&R "The C Prog language"Ex1-6

c - K&R 1.19 练习 ("reverse"函数)

mysql - 从 XML 文件中获取数据并将其放入 MySQL 数据库

c - 函数声明与原型(prototype)的替代 (K&R) C 语法