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

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

本题出自K&R《C程序设计语言》,练习1-12:编写一个程序,以每行一个单词的形式打印其输入。

这里对单词的定义比较宽松,它是任何其中不包含空格、制表符或换行符的字符序列。

一开始的想法是:

#include <stdio.h>

int main(void)
{
    int c;
    while ((c = getchar()) != EOF)
    {
        if (c == ' ' || c == '\t' || c == '\n')
        {
            putchar('\n');
        }
        else
        {
            putchar(c);
        }
    }

    system("pause");
    return 0;
}

但是,连续出现空格或制表符时,将会出现如下情况:

结果中会出现有的行中没有单词,这不符合题目要求的“每行一个单词”,因此需要修改程序。有必要记录“连续出现空格或制表符”的情况,因此需要一个变量来记录状态。修改之后的程序如下:

#include <stdio.h> 

#define INSPACE 1  // in space
#define NOT_INSPACE 0  // not in space

int main(void)
{
    int c; 
    int state = NOT_INSPACE; 

    while ((c = getchar()) != EOF)  // while c is not EOF
    {
        if (c == ' ' || c == '\t' || c == '\n')  
        {
            if (state == NOT_INSPACE)
            {
                state = INSPACE; 
                putchar('\n'); 
            }
            else
            {
                ;  // else, don't print anything
            }
        }
        else
        {
            state = NOT_INSPACE;
            putchar(c); 
        }
    }

    system("pause");
    return 0;
}

运行结果如下:

猜你喜欢

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