【问题标题】:K&R C Exercise 1-9 *almost* solvedK&R C 练习 1-9 *几乎*已解决
【发布时间】:2016-02-02 17:52:23
【问题描述】:

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

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

【问题讨论】:

  • 我很好奇你为什么在开始 while 循环之前执行 getchar() ?你最终会丢弃一个角色。
  • 好吧,您在 return 0 之前缺少一个右大括号,以平衡您的 while 循环。除此之外,此代码在您决定预期输出时起作用。
  • 正如最后两个 cmets 所说的那样正确,它会起作用。虽然if (s != 0) 是不必要的,但无论如何设置s = 0
  • 也许测试if (c == ' ') { if (s == 0) {s++; putchar (c); } } else ... 可以提供一个途径。另一种方法是捕获前一个字符,然后它可以是一个简单的if (p != ' ') putchar(c); else if (c != ' ') putchar (c); p = c;
  • 我将while ((c = getchar()) != EOF) 更改为while (c != EOF),现在我得到了无限的垃圾输出流。关于前者的某些事情正在终止循环 - 我如何在不丢失角色的情况下做到这一点?

标签: c loops io


【解决方案1】:

不要丢弃第一个char@David Hoelzer

// Commented out
//c = getchar();

s = 0;
while ((c = getchar()) != EOF){

还要注意} 附近的不平衡return 0;

【讨论】:

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