C语言学习 - 0002 优秀代码学习

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3  
 4 #define INI_LEN 20
 5 #define INC 10
 6 char* get_input();
 7 void output(char* array);
 8 int main(){
 9     printf("请输入字符串,双回车结束:\n");
10     char *string = get_input();
11      
12     output(string);
13     getchar();
14     return 0;
15 }
16 //输入函数
17 char* get_input(){
18     char* string = (char*)malloc(INI_LEN*sizeof(char));
19     int len = INI_LEN;
20     int i = 0,cnt = 0;
21     while (cnt != 2){
22         if (i + 1 == len){
23             len += INC;
24             char* tmp = string;
25             string = (char*)malloc(len*sizeof(char));
26             for (int k = 0; k <= i; ++k)
27                 string[k] = tmp[k];
28             free(tmp);
29         }
30         string[i] = getchar();
31         if (string[i] == '\n')
32             cnt++;
33         else
34             cnt = 0;
35         i++;
36     }
37     string[i-1] = '\0';
38     return string;
39  
40 }
41 //输出函数
42 void output(char* array){
43     int tag = 1,cnt = 1;
44     for (int i = 0; array[i]!='\0'; ++i){
45         if (tag == 1){
46             tag = 0;
47             if (array[i] != '\n'&&array[i] != '\0')
48                 printf("%d.  ", cnt);
49         }
50         if (array[i] == '\n'){
51             if (array[i+1] != '\n'&&array[i+1] != '\0'){
52                 tag = 1;
53                 cnt++;
54             }
55         }
56         printf("%c", array[i]);
57     }
58 }

 

posted @ 2015-11-12 17:56  Yx37412  阅读(280)  评论(0编辑  收藏  举报