gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:38 25 4
gpt4 key购买 nike

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

 #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() 方法轻松做到这一点,但我只是想知道我在这个实现中做错了什么。

最佳答案

第一个跳出来的错误:

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

将始终返回 true。你要&& ,或者使用 !()围绕你使用其他地方的整个条件,为了对称。

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

关于c - 使用 IN/OUT 标志每行显示一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52841066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com