thank you
< div class = " aw-list-img >
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int n;
while(scanf("%d",&n!=EOF))
{
char a[30][30];
char t[30];
int i,j;
for(i=0;i<n;i++)
scanf("%s",&a[i]);
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
if(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;i<n;i++)
printf("%s ",a[i]);
printf("\n");
}
return 0;
}
0 Answer
thank you
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
thank you
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;
}
thank you
这家伙很懒,什么都没留下...