Last active
August 29, 2015 14:17
-
-
Save trickart/1f2c1913f37d11715558 to your computer and use it in GitHub Desktop.
a example in chapter 1, section9 of K&R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define MAXLINE 1000 | |
int getline(char line[], int maxline); | |
void copy(char to[], char from[]); | |
/*最も長い入力行を印字する*/ | |
main() | |
{ | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment