#include <stdio.h> #include <stdlib.h> typedef enum {false=0,true=1}bool; #include <string.h> #define BUFFER_LEN 100 #define NUM_P 5 char buffer[BUFFER_LEN]; char *pS[NUM_P]={NULL}; char *pTemp =NULL; int i=0; bool sorted=false ; int last_string =0; int main(void) { printf(" Enter successive lines,pressing Enter at the "); while ((*fgets(buffer,BUFFER_LEN,stdin)!=' ')&&(i<NUM_P)) { pS[i]=(char*)malloc(strlen(buffer)+1); if(pS[i]==NULL) { printf("Memory allocation failed.Program terminated. "); return 1; } strcpy(pS[i++],buffer); } last_string=i; while(!sorted) { sorted=true; for(i=0;i<last_string-1;i++) { if(strcmp(pS[i],pS[i+1])>0) { sorted=false; pTemp=pS[i]; pS[i]=pS[i+1]; pS[i+1]=pTemp; } } } printf(" You input sorted in order is: "); for(i=0;i<last_string;i++) { printf("%s ",pS[i]); free(pS[i]); pS[i]=NULL; } system("pause"); return 0; }
fgets()函数用于从文件流中读取一行或指定个数的字符,其原型为: char * fgets(char * string, int size, FILE * stream); 参数说明: string为一个字符数组,用来保存读取到的字符。 size为要读取的字符的个数。如果该行字符数大于size-1,则读到 size-1 个字符时结束,并在最后补充' ';如果该行字符数小于等于 size-1,则读取所有字符,并在最后补充 '