首页 文章

编译器不在codeblock中执行程序

提问于
浏览
-5

我正在编写一个代码,用于打印由我输入的字符串中最长的单词 . 但是程序没有执行,并且收到错误消息以关闭程序 .

#include<stdio.h>
#include<string.h>
int main(){
    char str[80]="in this program we will find the longest keyword used so that we can";
    int longest=0;
    char word[25];
    char longestword[25];
    int i=0,j;
    while(str[i]!='\0' && str[i]!=' '){
        j=0;
        while(str[i]!='\0' && str[i]!=' '){
            word[j++] = str[i++];
        }

        word[j] = '\0';
        if (strlen(word) > longest){
            longest = strlen(str);
            strcpy(longestword,longest);
        }
        if(str[i]==' '){
            i++;
        }
        printf("longest word is :\n",longestword);
        printf("length is:\n", longest);
        return 0;
    }
}

我附上此截图 .
written code

windows error message

2 回答

  • 0

    这是我改写的代码 - 答案---`

    #include <stdio.h>
    #include <string.h>
    
    int main(){
       char my_str[] = "in this program we will find the longest keyword used so 
       that we can";
    
    
    int longest = 0; 
    char word[20];      
    char longestWord[20]; 
    
    int i = 0, j;
    
    while(my_str[i]!='\0'){
        j = 0;
        while(my_str[i]!=' ' && my_str[i]!='\0'){
            word[j++] = my_str[i++];
        }
               word[j] = '\0';
        if (strlen(word) > longest){
            longest = strlen(word);
            strcpy(longestWord, word);
        }
    
        if (my_str[i] == ' '){
            i++;
        }
    }
    printf("Longest word: %s\n", longestWord);
    printf("Length: %d\n", longest);
    
    return 0;
    }
    
  • 0

    这不是't codeblock'的错误 . 你的程序开始实际运行,但随后它崩溃(由于segmentation fault)和windows / codeblock显示此"... has stopped working"消息 .

    导致崩溃的实际行是 longest

    strcpy(longestword,longest);
    

    我相信你的意思是 longestword .

    还要注意你的代码在语法(在执行它之前读取编译器的警告)和逻辑中都有更多的错误 .

相关问题