0

我已经开始学习 Dennis Ritchie 和 Brian W.Kernighan 的“The ANSI C Programming Language”。到目前为止,我刚刚学习了 getchar()、putchar()、while、for、if。有一个练习,我必须只使用我现在学到的东西来做。以上是我唯一知道的。这是书中出现的练习:

练习 1-9。编写一个程序,将其输入复制到其输出,用一个空格替换每个包含一个或多个空格的字符串。

我知道 C#、Pascal、Objective-C 和一些 Java,但我不明白如何在不使用数组的情况下解决这个问题。我知道数组,但由于作者尚未涵盖数组,但我认为我不能使用它们。数组将在下一章中讲授。

4

4 回答 4

2

实现 Nikolai 的解决方案,因为在代码中可能更容易理解,

#include <stdio.h>
#include <stdbool.h> /* C99, but a good idea to use nonetheless */

int main() {
    bool was_space; /* state variable */
    char c; /* one-character buffer */

    while ( ( c = getchar() ) != EOF ) {
        if ( ! was_space || c != ' ' ) putchar( c );
        was_space = c == ' ';
    }
    return 0;
}

http://ideone.com/LLmBh

如果你真的想避免bool,你可以int改用。

于 2012-05-18T12:24:06.963 回答
1

打印您看到的第一个空格(空白)字符,跳过其余部分。这意味着有一个布尔变量,false当你看到一个非空白字符时设置为,并true在你点击并打印第一个空格时设置为。如果该变量是 ,则不要打印true。一种两态“状态机”。

于 2012-05-18T12:13:41.080 回答
1

基于我的评论的示例:

#include <stdio.h>

int main()
{
    int previous_char = 0;
    int latest_char;

    while ((latest_char = getchar()) != EOF)
    {
        if (' ' != previous_char || ' ' != latest_char)
        {
            putchar(latest_char);
        }
        previous_char = latest_char;
    }
    return 0;
}

请注意,getchar()返回并putchar()接受一个int,而不是char

于 2012-05-18T15:19:02.257 回答
0

After some time I realised that I'd misunderstood the question and this misunderstanding was because I did not fully understand the mechanism of getchar() and putchar() functions. At first I thought I had to take the whole string and then itearte through it. But then I understood that "while ((input_char = getchar()) != EOF)" does some kind of iteration (maybe a simulation of iteration, don't know for sure). After that the rest is just a normal logic. When you look at the code you'll probably notice that I did not use if-else pattern. That's simply because "If" is the only thing that I've got so far and I should not use anything else that I know from other programming languages(although I'm sure if-else is found in any language). We have not seen &&,||,boolean either. And also I used ++counter instead of counter++. That's also because we have not yet come to post increment. I know it's the simplest logic that everyone knows but I wanted to share anyway.

#include <stdio.h>
int main()
{
   int input_char;
   int counter = 0;
   while ((input_char = getchar()) != EOF)      
   {
     if (input_char == ' ')
     {
        ++counter;
        if (counter == 1)
          putchar(input_char);
     }

     if (input_char != ' ')
     {
        putchar(input_char);
        counter = 0;
     }
   }
  return 0;
}          
于 2012-05-19T06:05:12.973 回答