C程序設計語言 練習1-16: 修改打印最長文本行的程序的主程序main,使之可以打印任意長度的輸入行的長度,並儘可能多地打印文本

未修改之前的程序

/* 讀取一組文本行,並把最長的文本行打印出來 */
#include <stdio.h>
#define MAXLINE 10  /* 允許的輸入行的最大長度 */

int get_line(char [], int);
void copy(char to[], char from[]);

/*  打印最長的輸入行  */
int main() {
    int len;    /*  當前行長度  */
    int max;    /*  目前爲止發現的最長行的長度  */
    char line[MAXLINE];    /*  當前的輸入行  */
    char longest[MAXLINE];    /*  用於保存最長的行數  */

    max = 0;
    while ((len = get_line(line, MAXLINE)) > 0) {
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    }
    if (max > 0) {  /*  存在這樣的行  */
        printf("最長行的長度: %d\n最長的行:\n%s", max, longest);
    } else {
        printf("不存在這樣的行");
    }
    return 0;
}


/*  get_line函數:將一行讀入到s中並返回其長度  */
int get_line(char s[], int lim) {
    int c, i;
    for (i = 0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i) {
        s[i] = c;
    }
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

void copy(char to[], char from[]) {
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0') {
        ++i;
    }
}

修改之後的程序:

/* C程序設計語言 練習1-16: 修改打印最長文本行的程序的主程序main,使之可以打印任意長度的輸入行的長度,並儘可能多地打印文本 */
#include <stdio.h>
#define MAXLINE 1000  /* 允許的輸入行的最大長度 */

int get_line(char [], int);
void copy(char to[], char from[]);

/*  打印最長的輸入行  */
int main() {
    int len;    /*  當前行長度  */
    int max;    /*  目前爲止發現的最長行的長度  */
    char line[MAXLINE];    /*  當前的輸入行  */
    char longest[MAXLINE];    /*  用於保存最長的行數  */

    max = 0;
    while ((len = get_line(line, MAXLINE)) > 0) {
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    }
    if (max > 0) {  /*  存在這樣的行  */
        printf("最長行的長度: %d\n最長的行:\n%s", max, longest);
    } else {
        printf("不存在這樣的行");
    }
    return 0;
}


/*  get_line函數:將一行讀入到s中並返回其長度  */
int get_line(char s[], int lim) {
    int c, i;
    int j;
    j = 0;
    for (i = 0; /*i < lim-1 &&*/ (c=getchar()) != EOF && c != '\n'; ++i) {
        if (i < lim - 2) {
            s[j++] = c;
        }
    }
    if (c == '\n') {
        s[j++] = c;
        ++i;
    }
    s[j] = '\0';
    return i;
}

void copy(char to[], char from[]) {
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0') {
        ++i;
    }
}

 

發佈了6 篇原創文章 · 獲贊 0 · 訪問量 289
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章