编写一个程序,读取输入,直到读入了10个字符串或遇到EOF,由二者中最先被满足的那个终止读取过程。这个程序可以为用户提供一个有5个选项的菜单:输出初始字符串列表、按ASCII顺序输出字符串、按长度递增顺序输出字符串、按字符串中第一个单词的长度输出字符串和退出。菜单可以循环,直到用户输入退出请求。当然,程序要能真正完成菜单中的各项功能。
#include <stdio.h> #include <string.h> #include <ctype.h> void origin_put(char **p, int n); void ascii_put(char **p, int n); void length_put(char **p, int n); int first_word_length(char *p); int first_word_length(char *p); void word_put(char **p, int n); int main(void) { char str[10][81]; char *p[10]; char command[10]; int n; while(1) { n = 0; puts("input no more than 10 strings finished by EOF (^Z):"); do { if ( gets(str[n]) == NULL ) break; p[n] = str[n]; n++; } while( n<10 ); puts("select:"); puts("a. put originally"); puts("b. put in order of ascii"); puts("c. put in order of string's length"); puts("d. put in order of first word's length"); puts("e. input strings again"); puts("q. quit"); do { gets(command); switch(command[0]) { case 'a': puts("put originally:"); origin_put(p,n); break; case 'b': puts("put in order of ascii:"); ascii_put(p,n); break; case 'c': puts("put in order of string's length:"); length_put(p,n); break; case 'd': puts("put in order of first word's length:"); word_put(p,n); break; case 'e': break; default : puts("Quit."); return 0; } } while( command[0] != 'e' ); } } void origin_put(char **p, int n) { int i; for(i=0; i<n; i++) puts(p[i]); } void ascii_put(char **p, int n) { int i,j; char *temp; for(i=0; i<n; i++) for(j=0; j<n-i-1; j++) if (strcmp( p[j], p[j+1] ) > 0) { temp = p[j]; p[j] = p[j+1]; p[j+1] = temp; } origin_put(p,n); } void length_put(char **p, int n) { int i,j; char *temp; for(i=0; i<n; i++) for(j=0; j<n-i-1; j++) if ( strlen(p[j]) > strlen(p[j+1]) ) { temp = p[j]; p[j] = p[j+1]; p[j+1] = temp; } origin_put(p,n); } int first_word_length(char *p) { int i=0; for (; !isalpha(*p); p++) if (*p == '\0') return 0; for (i=1; isalpha(p[i]); i++) continue; return i; } void word_put(char **p, int n) { int i,j; char *temp; for(i=0; i<n; i++) for(j=0; j<n-i-1; j++) if ( first_word_length(p[j]) > first_word_length(p[j+1]) ) { temp = p[j]; p[j] = p[j+1]; p[j+1] = temp; } origin_put(p,n); }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题