【Coding】讀入一組文本行,並把最長的文本行打印出來

本例來源於《C程序設計語言》1.9節—字符數組。

編寫的基本框架是:

while (還有未處理的行)
if (該行比已處理的最長行還要長)
    保存該行
    保存該行的長度
打印最長的行

 代碼如下:

#include <stdio.h>

#define MAXLINE 1000   // 允許的輸入行的最大長度

int getline(char line[], int maxline);  
void copy(char to[], char from[]);  

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

    max = 0; 
    while ((len = getline(line, MAXLINE)) > 0)  // 如果當前行的長度大於0
    {
        if (len > max)
        {
            max = len; 
            copy(longest, line); 
        }
        //if (max > 0)
        //{
        //    printf("%s", longest); 
        //}
    }

    printf("%s", longest);

    system("pause"); 
    return 0; 
}

/* getline函數:將一行讀入到line中,並返回其長度 */
int getline(char line[], int maxline)
{ 
    int c;

    int i; 
    for (i = 0; i < maxline - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
    {
        line[i] = c; 
    }
    if (c == '\n')
    {
        line[i] = c; 
        ++i; 
    }
    line[i] = '\0'; 

    return i; 
}

/* copy函數:將from複製到to,這裏假定to足夠大 */
void copy(char to[], char from[])
{  
    int i = 0; 

    while ((to[i] = from[i]) != '\0')
    {
        ++i; 
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章