weixin_50947427 2021-08-04 23:03 采纳率: 66.7%
浏览 24
已结题

请教这个程序为什么还满足条件就退出了这个for循环?

当i=2时正常执行循环内语句,但执行完之后就退出了,甚至都不执行i++。
把i<=strlen(pa)换成i<=len这个循环又正常了。
这是怎么回事?
代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char key[1000005],pa[10000005],word[1000005];
int main(){
    gets(key);
    gets(pa);
    int f=0,count=0,index=-1,len=strlen(pa);
    for(int i=0;i<=strlen(pa);i++){
        if(pa[i]==' '||pa[i]=='\0'){
            pa[i]='\0';
            strcpy(word,&pa[f]);
            if(strcasecmp(key,word)==0){
            count++;
            if(index==-1){
                index=f;
            }
        }
            f=i+1;
        }
    }
    if(count==0){
        cout<<-1;
    }
    else{
        cout<<count<<' '<<index;
    }
    return 0;
}

输入:
To
to be or not to be is a question

  • 写回答

1条回答 默认 最新

  • 没事干写博客玩 2021-08-05 02:31
    关注

    for循环条件每次进入循环都会判断,你在for里修改了pa,所以当再次执行strlen(pa)时跳出循环

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月13日
  • 已采纳回答 8月5日
  • 创建了问题 8月4日