forked from steven-schronk/C-Programming-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex_5-7.c
More file actions
69 lines (59 loc) · 1.41 KB
/
ex_5-7.c
File metadata and controls
69 lines (59 loc) · 1.41 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
#include <string.h>
#define MAXLINES 1000 // max number of lines in buffer
#define MAXLEN 1000 // max length of individual lines
// declare lines as an array of array of char
// iow: create the maximum size empty buffer in global scope
char lines[MAXLINES][MAXLEN];
/* print contents of array */
void print_sparse_array(char s[][MAXLEN])
{
int i, j;
for(i = 0; i < MAXLINES; i++)
{
int found = 0;
for(j = 0; j < MAXLEN; j++)
{
if(s[i][j] != '\0') { found++; }
}
if(found > 0)
{
printf("%d:\t", i);
for(j = 0; j < MAXLEN; j++)
printf("%c", s[i][j]);
printf("\n");
}
}
printf("\n");
}
/* From K&R Page 29 */
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;
s[i] = '\0';
return i;
}
/*
reads input lines from stdin and stores each line in buffer named lines
*/
int readlines(char lines[][MAXLEN], int maxlines)
{
int len, nlines = 0;
while((len = getline(lines[nlines], MAXLEN)) > 0)
if(nlines >= maxlines) // when buffer full, return
return -1;
else
lines[nlines++][len - 1] = '\0'; // delete newline
return nlines;
}
int main()
{
int length = readlines(lines, MAXLINES);
printf("Number of Lines Stored: %d\n", length);
print_sparse_array(lines);
return 1;
}