使用putchar和getchar在C中删除多个空格

时间:2014-11-29 17:41:51

标签: c string getchar putchar

问题:编写一个使用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 == ' ')
                ;
        }
    }   
}

当一个字符串包含空格时,它会停止。我不确定应该如何调试它。我认为问题在于我的第二个while,程序进入无限循环而不是等待新的字符。

5 个答案:

答案 0 :(得分: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()中的最后一个红色字符。

答案 1 :(得分:2)

Anonymous的答案有效,但有一个更简单的算法也可以使用:

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

答案 2 :(得分: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;
}

答案 3 :(得分:0)

这对我有用。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;
    int space = 0;

    while ((c = getchar())!= EOF){

            if (c != ' '){
                putchar(c);
            }else{
                if(space == ' '){
                    continue;
                }else{
                    putchar(c);
                }
            }
            space = c;
    }
    return 0;
}

答案 4 :(得分:0)

您的计划存在一些问题:

  • main()的原型必须包含返回类型int

  • c必须定义为int,以便您可以正确区分EOFgetchar()返回的所有有效字节值。

  • 识别出空白字符后,您必须继续阅读字符并跳过后续空白。

  • 从技术上讲,空白字符包括空格字符' '和制表符'\t'。您应该使用isblank()中的<ctype.h>并修改您的程序以跳过后续的空白字符。

以下是修改后的版本:

#include <ctype.h>
#include <stdio.h>

/* replaces multiple blanks with a single blank */
int main(void) {
    int c;
    while ((c = getchar()) != EOF) {
        putchar(c);
        if (isblank(c)) {
            while (isblank(c = getchar())
                continue;
            if (c == EOF)
                break;
            putchar(c);
        }
    }
    return 0;
}