0
Follow
0
View

What's wrong with Experiment 7 8999

dingashuai 注册会员
2023-02-27 22:15
< div class = "md_content_show e397 data - v - 3967" = "" >

thank you

dyfdyfdyf 注册会员
2023-02-27 22:15

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > this code is a brace position error, there was a problem leads to read input. Specifically, the following line of code:

while(scanf("%d",& n! =EOF))

should be changed to:

while(scanf("%d",& n)! =EOF)

puts the parentheses that determine whether the input ends in the correct position. The modified code is as follows:

#include 
#include 
#include 

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        char a[30][30];
        char t[30];
        int i,j;
        for(i=0;iscanf("%s", a[i]);
        for(i=1;ifor(j=0;jif(strcmp(a[j],a[j+1])>0)
                {
                    strcpy(t,a[j]);
                    strcpy(a[j],a[j+1]);
                    strcpy(a[j+1],t);
                }
        }
        for(i=0;iprintf("%s ",a[i]);
        printf("\n");
    }
    return 0;
}


Also, it is recommended to use scanf with a limit on the maximum read length to avoid array out-of-bounds problems. For example:

scanf("%29s", a[i]);  // 最大读入长度为29


isabel333 注册会员
2023-02-27 22:15
< div class = "md_content_show e397 data - v - 3967" = "" >

thank you

ddpaopaovip 注册会员
2023-02-27 22:15

This answer quotes ChatGPT

Refer to this code

#include 
#include 
#include 

int cmp(const void* a, const void* b) {
    return strcmp(*(char**)a, *(char**)b);
}

int main() {
    int n;
    char str[30];
    char* names[30];

    while (scanf("%d", &n) == 1) {
        getchar();
        for (int i = 0; i < n; i++) {
            fgets(str, 30, stdin);
            int len = strlen(str);
            if (str[len - 1] == '\n') str[len - 1] = '\0';  // 去掉换行符
            names[i] = (char*)malloc(sizeof(char) * (len + 1));  // 动态分配空间
            strcpy(names[i], str);
        }
        qsort(names, n, sizeof(char*), cmp);
        for (int i = 0; i < n; i++) {
            printf("%s ", names[i]);
            free(names[i]);  // 释放动态分配的空间
        }
        printf("\n");
    }

    return 0;
}


cx8311841 注册会员
2023-02-27 22:15
< div class = "md_content_show e397 data - v - 3967" = "" >

thank you

Mr_Sun73 注册会员
2023-02-27 22:15

line 7 the scanf(" % d", & amp; n! =EOF) instead of
(scanf("%d",& n)! =EOF)

About the Author

Question Info

Publish Time
2023-02-27 22:15
Update Time
2023-02-27 22:15