使用IN / OUT标志每行显示一个单词一个字符串

时间:2018-10-16 17:35:30

标签: c arrays string

我编写了一个程序,该程序首先存储来自用户的任意数量的文本行。之后,它将检查何时有新单词出现,如果有,则将其打印在新行中。 下面是我的代码:

 #include<stdio.h>
 #define IN 1   //inside a word
 #define OUT 0  //outside a word

int main()
{
  char s[100];   //storing the string entered by user
  int c;         //getchar reading variable
  int i=0;       //iterating variable

  while((c=getchar())!=EOF)
  {
    s[i++]=c;
  }
  s[i]='\0';   //end of string


  i=0;
  int p=0;    //stores the start of the word
  int current=OUT; //flag to indicate if program is inside or outside a word

  while(s[i]!='\0')  
  {
    if(current==OUT)  //when program is outside a word
    {
        if(s[i]!=' ' || s[i]!='\n' || s[i]!='\t')  //word found
        {
            p=i;  //store starting position of word 
            current=IN;
        }
    }
    else if(current==IN) //program is inside a word
    {
        if(s[i]==' ' || s[i]=='\n' || s[i]=='\t') //end of word found
        {
            current=OUT; //flag now outside the word
            for(int j=p;j<i;j++) //print from starting position of word
            {
                printf("%c",s[j]);
            }

            printf("\n");  //go next line

        }

    }
    ++i;  //incremnent the iterator variable
 }

return 0;
}

如果我以适当的方式(即没有任何多余的空格或换行)输入字符串,那么我的程序就可以很好地运行。 但是,如果我按如下方式输入一行(注意多余的空格和换行):

*我是男孩

我去了日本* /

然后,它还会打印这些多余的换行符和空格以及单词,根据我的说法,由于IN和OUT标志,这种情况不应发生。 输出如下: enter image description here 我请你帮我。

我知道我可以轻松地通过一次检查一个字符的putchar()方法来做到这一点,但是我只是好奇我在此实现中做错了什么。

2 个答案:

答案 0 :(得分:2)

第一个跳到我身上的错误:

if(s[i]!=' ' || s[i]!='\n' || s[i]!='\t')

将始终返回true。您想使用&&,或者在其他条件下使用!()来保持对称。

或者更好的是,将其分解为函数,或使用isspace中的<ctype.h>

答案 1 :(得分:0)

您用于确定字符是否为空格的过滤条件不正确。 ||运算符表示OR。使用链式OR可使表达式每次都评估为true。您需要AND运算符&&。一旦一个操作数的值为假,and运算符就会失败,或者对于C,0就失败了。

除此之外,还有更好的方法来检查空白。一种想法是使用<ctype.h>中的isspace函数,该函数接受一个字符作为int,也可以是unsigned char,并确定该字符是否为{ {1}}。您还可以通过switch语句进行字符检查

' ', '\t', '\v', '\n' or '\r'