编写一个函数,读入10个字符串或者读到EOF停止。该程序为用户提供一个有5个选项的菜单:打印源字符串列表、以ASCⅡ中的顺序打印字符串、按长度递增顺序打印字符串、按字符串中第1个单词的长度打印字符串、退出。菜单可以循环显示除非用户选择退出选项。当然,该程序要能真正完成菜单中个选项的功能。
代码如下:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE 81
void showmenu(void);
void orgseq(char **, int);
void byASC(char **, int);
void bylen(char **, int);
void byfstlen(char **, int);
int main(void)
{
char str1[SIZE], str2[SIZE], str3[SIZE], str4[SIZE], str5[SIZE];
char str6[SIZE], str7[SIZE], str8[SIZE], str9[SIZE], str10[SIZE];
char * ptr[10] = {str1, str2, str3, str4, str5, str6, str7, str8, str9, str10};
int i = 0;
char ch;
printf("Enter 10 arrays or control + z to end\n"); //输入10个字符串或者EOF退出
while(i < 10)
{
if(!fgets(ptr[i], SIZE, stdin))
break;
i++;
}
printf("Please choose the function:\n");
showmenu();
ch = getchar();
if(ch != '\n')
while(getchar() != '\n')
continue;
else
while(isspace(ch = getchar()))
continue;
while(ch != 'q')
{
switch (ch){
case 'a': orgseq(ptr, 10);
printf("Enter another choice(q to quit): ");
showmenu();
break;
case 'b': byASC(ptr, 10);
printf("Enter another choice(q to quit): ");
showmenu();
break;
case 'c': bylen(ptr, 10);
printf("Enter another choice(q to quit): ");
showmenu();
break;
case 'd': byfstlen(ptr, 10);
printf("Enter another choice(q to quit): ");
showmenu();
break;
}
ch = getchar();
if(ch != '\n')
while(getchar() != '\n')
continue;
else
while(isspace(ch = getchar()))
continue;
}
return 0;
}
void showmenu(void)
{
printf("a) print in original sequence b) print according to ASCⅡ\n");
printf("c) print by the length d) print by the length of the first word\n");
printf("q) quit\n");
return;
}
void orgseq(char ** ptr, int n)
{
int i = 0;
for(i = 0; i < n; i++)
printf("%s", ptr[i]);
}
void byASC(char ** ptr, int n)
{
int i, j;
char *temp;
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - 1-i; j++)
{
if(*ptr[j] > *ptr[j+1])
{
temp = ptr[j];
ptr[j] = ptr[j+1];
ptr[j+1] = temp;
}
}
}
for(i = 0; i < n; i++)
printf("%s", ptr[i]);
}
void bylen(char ** ptr, int n)
{
int i, j;
char *temp;
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - 1 - i; j++)
{
if(strlen(ptr[j]) > strlen(ptr[j+1]))
{
temp = ptr[j];
ptr[j] = ptr[j+1];
ptr[j+1] = temp;
}
}
}
for(i = 0; i < n; i++)
printf("%s", ptr[i]);
}
void byfstlen(char ** ptr, int n)
{
int i, j;
char *temp;
char **pst = ptr;
int fst_len[n];
char exchange;
for(i = 0; i < n; i++)
{
j = 0;
fst_len[i] = 0;
while(!isspace(*(*pst + j)))
{
j++;
fst_len[i]++;
}
pst++;
}
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - 1 - i; j++)
{
if(fst_len[j] > fst_len[j+1])
{
temp = ptr[j];
ptr[j] = ptr[j+1];
ptr[j+1] = temp;
exchange = fst_len[j];
fst_len[j] = fst_len[j+1];
fst_len[j+1] = exchange;
}
}
}
for(i = 0; i < n; i++)
printf("%s", ptr[i]);
}