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

标签 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 上,程序在那里进入无限循环而不是等待新字符。

最佳答案

#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() 中的最后一个红色字符。

关于c - 在 C 中使用 putchar 和 getchar 删除多个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27205071/

相关文章:

c - 当我按 ASCII 十进制代码打印输入的字符时,会打印奇怪的 10 值

c - 在变量参数函数中使用字符串指针

c - 使用 sscanf 读取带空格的字符串

python - Cygwin 安装程序不安装 gdb.exe

C#/.NET : Can I get a string of valid HTML from a Stream?

string - 如何创建字符串作为另一个列表的一部分的列表

linux - 使用sed将元音从大写转换为小写,将小写转换为大写

c - 为什么 getchar 没有退出?

c - 为什么我在 Raspberry-Pi Jessie Lite 上启动时无法访问标准输入?

c - 如何确保动态分配的数组在 openmp 中是私有(private)的