-
Notifications
You must be signed in to change notification settings - Fork 2
/
longest_line.c
51 lines (43 loc) · 1.1 KB
/
longest_line.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#define MAXLINE 1000
int get_line(char line[], int maxline);
void copy(char to[], char from[]);
int main()
{
int len; // current line length
int max; // max line length so far
char line[MAXLINE]; // current input line
char longest[MAXLINE]; // copy of longest line so far
max = 0;
while ((len = get_line(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
// 当涉及到from-to的copy时候,最好使用void型函数,这样实现更简单
}
if (max > 0)
printf("longest line: %s", longest);
return 0;
}
/*函数实体中的变量名称可以和前面declared的不同*/
int get_line(char s[], int lim)
{
int c, i;
for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
printf("the 'i' after the for loop is %d\n", i);
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0'; // 字符串的结尾必须是\0, 没有实际意义 但是占用内存空间
return i;
}
/*函数argument中的数组最好不要限定长度*/
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}