K& R C练习1-9 *几乎*解决了

时间:2016-02-02 17:52:23

标签: c loops io

K& R C练习1-9陈述:

  

编写一个程序将其输入复制到其输出中,用一个空格替换一个或多个空格的每个字符串。

我几乎解决了这个练习,但是我写的代码(见下文)总是在第一个非空格字符之前打印一个额外的空格。所以看起来像这样的输入

  

X(空间)(空间)X(空间)(空间)X(空间)(空间)X

导致输出看起来像这样

  

(空间)X(空间)X(空间)X(空间)X

#include <stdio.h>

int main()
{
    int c;                     //current input character
    int s;                     //consecutive input space counter

    c = getchar();
    s = 0;
    while ((c = getchar()) != EOF){
        if (c == ' '){
            ++s;
            if (s == 1)        //uses the counter to print only the  
                putchar(' ');  //first space in each string of spaces
        }
        else {
            putchar(c);
            if (s != 0)            //resets the space counter when it  
                s = 0;             //encounters a non-space input character
        }
    }
    return 0;
}

为什么我的代码在运行时始终会打印出前导空格? 如何修改此代码以首先打印第一个输入字符而不是前导空格?

1 个答案:

答案 0 :(得分:0)

不要丢弃第一个DateTime@David Hoelzer

char

另请注意// Commented out //c = getchar(); s = 0; while ((c = getchar()) != EOF){

附近的不平衡}