C程序设计语言 练习1-9

版权声明:转载时打个招呼。 https://blog.csdn.net/qq_15971883/article/details/87996494

题目

编写一个将输入复制到输出的程序,并将其中连续的多个空格用一个空格代替。

分析

连续的多个空格中,第一个出现的空格,输出,此后的空格,不输出。此题可以使用Flag法。

代码

#include <stdio.h>
/* 
    Write a program to copy its input to its output,
    replacing each string of one or more blanks by a single blank.
*/
int main(void)
{ 
    int c;  // 定义整型变量c,用以保存输入的字符
    int Flag = 0;  

    while ((c = getchar()) != EOF)  // 当输入的字符c不是文件结束符EOF时,执行循环语句
    {
        if (c != ' ')
        {
            putchar(c);
            Flag = 0;
        }
        else
        {
            if (Flag == 0)
            {
                putchar(c);
                Flag = 1;
            }
        }
    }

    system("pause"); 
    return 0; 
}

猜你喜欢

转载自blog.csdn.net/qq_15971883/article/details/87996494