求大神帮小白找c语言bug所在?

找出字符串中的最长单词并输出:

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[]) {
    
    char str[] = "adventure may hurt you but monotony will kill you";
    char *p;
    int count = 0;
    int maxlen = 0;
    int lenth = 0;
    int maxIndex = 0;
    for ( p = str ; *p!= '\0' ; p++) {
        
        if (*p != ' ') {
            lenth++;
        }else{
            
            if (lenth >= maxlen) {
                maxlen = lenth;
                maxIndex = count;
                lenth = 0;
            }
            
        }
        count++;
    }
    for (int i = 0; i < maxlen; i++) {
        printf("%c",str[maxIndex-maxlen+i]);
    }
    
    return 0;
}
阅读 2.7k
1 个回答

if (lenth >= maxlen) {

        maxlen = lenth;
        maxIndex = count;
        lenth = 0;
    }else{
    lenth=0;

}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进