Write a program to prompt the user to enter a set of strings and the program would sort and display them in ascending alphabetical order. It is accepted to use the functions in the string.h library in the program. Here is a sample run. --------------------------------------------------------- How many strings you are going to enter?: 4 Enter Strings One by One: Nanjing Shanghai Chengdu Chongqing Order of Sorted Strings: Chengdu Chongqing Nanjing Shanghai ---------------------------------------------------------
时间: 2023-08-15 08:39:34 浏览: 98
Sure, here's a C program that prompts the user to enter a set of strings, sorts them in ascending alphabetical order, and displays them:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 100
#define MAX_STR_NUM 100
int compare_strings(const void* a, const void* b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main() {
int num_strings;
char buffer[MAX_STR_LEN];
char* strings[MAX_STR_NUM];
printf("How many strings you are going to enter?: ");
scanf("%d", &num_strings);
printf("Enter Strings One by One:\n");
for (int i = 0; i < num_strings; i++) {
scanf("%s", buffer);
strings[i] = strdup(buffer); // allocate memory and copy string
}
qsort(strings, num_strings, sizeof(char*), compare_strings);
printf("Order of Sorted Strings:\n");
for (int i = 0; i < num_strings; i++) {
printf("%s\n", strings[i]);
free(strings[i]); // free allocated memory
}
return 0;
}
```
The `compare_strings` function is used by `qsort` to compare two strings. The `strings` array is an array of pointers to strings, where each pointer points to a dynamically allocated string (using `strdup`). After sorting the strings, we simply print them out and free the memory allocated for each string.
阅读全文