I am going through this book and have hit some examples that I am not sure how to test from chapter 1. They have you reading in lines and looking for different characters but I have no idea how to test the code in C that I have made.
For example:
/* K&R2: 1.9, Character Arrays, exercise 1.17
STATEMENT:
write a programme to print all the input lines
longer thans 80 characters.
*/
<pre>
#include<stdio.h>
#define MAXLINE 1000
#define MAXLENGTH 81
int getline(char [], int max);
void copy(char from[], char to[]);
int main()
{
int len = 0; /* current line length */
char line[MAXLINE]; /* current input line */
while((len = getline(line, MAXLINE)) > 0)
{
if(len > MAXLENGTH)
printf("LINE-CONTENTS: %s\n", line);
}
return 0;
}
int getline(char line[], int max)
{
int i = 0;
int c = 0;
for(i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i)
line[i] = c;
if(c == '\n')
line[i++] = c;
line[i] = '\0';
return i;
}
I have no idea how to create a file with varying line lengths to test this on. After doing some research I saw someone try it this way:
[arch@voodo kr2]$ gcc -ansi -pedantic -Wall -Wextra -O ex_1-17.c
[arch@voodo kr2]$ ./a.out
like htis
and
this line has more than 80 characters in it so it will get printed on the terminal right
now without any troubles. you can see for yourself
LINE-CONTENTS: this line has more than 80 characters in it so it will get printed on the
terminal right now without any troubles. you can see for yourself
but this will not get printed
[arch@voodo kr2]$
But I have no idea how he manages it. Any help would be greatly appreciated.
This is the line that tells you everything you need to know about your getline() function.
It will read character by character and store it in the array until:
max - 1. Otherwise they’ll not be copied. In your example max = 1000 hence only 999 characters are input.