C 找出段落中最长的一行

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void clrArr(char arr[]);
int main(){
    char ch;
    char maxLine[200];//用于装载最长的一行 //假设最长行字符数不超过200
    int max=0;//记录已发现的最长字符个数
    
    int i=0;//记录每行的字符数
    char line[200];
    
    char* filename="D:/23.txt";
    FILE *fp;
    if((fp=fopen(filename,"r"))==NULL){
        printf("error");
    }

    clrArr(maxLine);

    while( !feof(fp)/*&&(ch=fgetc(fp))!=EOF*/  ){
        ch=fgetc(fp);
        if(ch=='\n'){//本行结束
            //在数组中存放都是实际字符 但是还不能就这样输出  因为没有结束符\0
            line[i++]='\n';
            line[i++]='\0';//如果不加上这个 对于VS VC就会有很多 烫 出现
            //即便是MINGW这里如果不处理也会很诡异

            printf(line);
            if(i>max){
                max=i;
                strcpy(maxLine,line);
                clrArr(line);
            }
            i=0;//准备新的一行
        }else{
            line[i]=ch;
            i++;
        }
    }
    printf("%s",maxLine);
    return 1;
}

void clrArr(char arr[]){
    int i=0;
    for(;i<200;i++){
        arr[i]=0;
    }
}

C教程原版

#include <stdio.h>
#include <stdlib.h>

int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* 打印最长的输入行 */
main() {

    int MAXLINE=1000;
    int len; /* 当前行长度 */
    int max; /* 至目前为止所发现的最长行的长度 */
    char line[MAXLINE]; /* 当前输入的行 */
    char longest[MAXLINE]; /* 用于保存最长的行 */
    max = 0;
    while ((len = getline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0) /* 有一行 */
        printf("%s", longest);
    return 0;
}
/* getline:将一行读入s中并返回其长度 */int getline(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;
}
/* copy:从from拷贝到to; 假定to足够大 */
void copy(char to[], char from[]) {
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

测试文档内容

Dashing through the snow
In a one horse open sleigh
O'er the fields we go
Laughing all the way
Bells on bob tails ring
Making spirits bright
What fun it is to laugh and sing
A sleighing song tonight

原文地址:https://www.cnblogs.com/cart55free99/p/2982645.html