輸出輸入行中的最長行

問題

輸出輸入行中的最長行

算法設計

主算法設計
  設最長行保存在maxStr中,其長度爲maxLen;
  讀入一行,假如存放在curStr中(*);
  求curStr的長度curLen;
  如果curLen > maxLen,則將curStr保存在maxStr中,maxLen=curLen;
  返回至*,直到讀入結束;
  打印maxStr。

算法實現一(字符數組)


#include <stdio.h>
#include <string.h>

#define MAXLINE	1024

int main( )	/* find longest line */
{
  int len;		/* current line length */
  int max;		/* maximum length seen so far */
  char line[MAXLINE];	/* current input line */
  char save[MAXLINE];	/* longest line saved */
  max = 0;
  /**
  gets在遇到文件結束(EOF)的時候返回NULL
  輸入EOF的方法:
  windows: ctrl+z
  linux: ctrl+D
  **/
  while( gets(line)  != NULL ){     
     len = strlen(line);
     if( len > max ) {
        max = len;
        strcopy(save, line);
     }
  }
  if( max > 0)
    printf(%s”, save);
  return 0;
}



算法實現二(字符串指針)

#include <stdio.h>
#include <string.h>

#define MAXLINE	1024

int main( )	/* find longest line */
{
  int len,  max;	/* current length and maximum length seen so far */
  char *curptr, *saveptr,*tmp; /* current  line pointer and longest line pointer saved */
  curptr = (char *)malloc(sizeof(char)*MAXLINE);
  saveptr = (char *)malloc(sizeof(char)*MAXLINE);
  max = 0;
  while( gets(curptr)  != NULL ){
        len = strlen(curptr);
        if( len > max ) {
           max = len;
           tmp = curptr;
           curptr = saveptr;
           saveptr = tmp; 
         }
  }
  if( max > 0)
      printf("%s", saveptr);
  free(curptr); free(saveptr); 
  return 0;
}

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