文章

19

粉丝

225

获赞

19

访问

43.5k

头像
C-(结构体数组)
P1217 同济大学机试题
发布于2023年3月22日 11:32
阅读数 1.9k

 用结构体数组来存取字符串,主要用到了strcmp()来比较字符串的顺序大小,用strcpy()来赋值,这里可以不用这个函数,用结构体定义一个变量即可,千万不要直接定义一个数组(char t[]),这样是不得行嘞。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node {
	char ch[30];
};
int main() {
	int n;
	scanf("%d", &n);
	//这里(struct node)*n的*n真的非常重要,不要忘记了,不然AC只有33%,就很奇怪
	struct node* str = (struct node*)malloc(sizeof(struct node)*n);
	for (int i = 0; i < n; i++) {
		scanf("%s", str[i].ch);
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n - i - 1; j++) {
			if (strcmp(str[j].ch, str[j + 1].ch) > 0) {
				char t[30];
				strcpy(t, str[j].ch);
				strcpy(str[j].ch, str[j + 1].ch);
				strcpy(str[j + 1].ch, t);
			}
		}
	}
	for (int i = 0; i < n; i++) {
		printf("%s\n", str[i].ch);
	}
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发