Skip to content

Instantly share code, notes, and snippets.

@trickart
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trickart/1f2c1913f37d11715558 to your computer and use it in GitHub Desktop.
Save trickart/1f2c1913f37d11715558 to your computer and use it in GitHub Desktop.
a example in chapter 1, section9 of K&R
#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