3

getchar()問題:複数の空白を削除した文字列を使用してテキスト入力を受け取り、出力するプログラムを作成してください。

擬似コードの書き方は次のとおりです。

While each input character is received before reaching EOF, do the following:
     1) if character is non-blank, print it out
     2) otherwise:
         a. print out the blank
         b. do nothing untill the next non-blank character 
     3) if a non-blank character is reached, go back to 1)

私はそのようにアルゴリズムを実装しようとしました:

#include <stdio.h>
/* replaces multiple blanks with a single blank */
main(){
    char c;
    while((c= getchar())!=EOF){
        if (c != ' ')
            putchar(c);
        else {
            putchar(c);
            while(c == ' ')
                ;
        }
    }   
}

文字列に空白が含まれていると、停止します。どのようにデバッグすればよいかわかりません。問題は 2 番目の にあると思います。whileプログラムは、新しい文字を待つのではなく、そこで無限ループに入ります。

4

5 に答える 5

3
#include <stdio.h>
/* replaces multiple blanks with a single blank */
main(){
    int c; // thanx chux
    while((c= getchar())!=EOF){
        if (c != ' ')
            putchar(c);
        else {
            putchar(c);
            while((c= getchar())!=EOF)
                if (c!=' ')
                {
                    putchar(c);
                    break;
                }
        }
    }   
}

最後に stdin から文字を読み取らなかったため、前の getchar() の最後の赤い文字を比較する無限ループが発生しました。

于 2014-11-29T17:45:49.260 に答える
2

匿名の答えは機能しますが、機能するはるかに単純なアルゴリズムもあります。

While there is input remaining:
    Read a character.
    If the current and previous characters aren't both blank:
        Print the current character.

C:

#include <stdio.h>

int main() {
    int prev = EOF, c;
    while ((c = getchar()) != EOF) {
        if (c != ' ' || prev != ' ')
            putchar(c);
        prev = c;
    }
    return 0;
}
于 2014-11-29T17:59:58.760 に答える
1
#include <stdio.h>

int main(void){
    int c;
    while((c = getchar())!=EOF){
        if (c != ' ')
            putchar(c);
        else {
            putchar(c);
            while((c = getchar()) == ' ')
                ;
            ungetc(c, stdin);//go back 1
        }
    }
    return 0;
}
于 2014-11-29T17:57:26.617 に答える