Reputation: 281
I tried to implement a solution for the exercise on the C language of K&R's book. I wanted to ask here if this could be considered a legal "solution", just modifying the main
without changing things inside external functions.
Revise the main routine of the longest-line program so it will correctly print the length of arbitrary long input lines, and as much as possible of the text.
#include <stdio.h>
#define MAXLINE 2 ////
int get_line1(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;
}
int main()
{
int len;
int max = MAXLINE;
char line[MAXLINE];
int tot = 0;
int text_l = 0;
while ((len = get_line1(line, max)) > 0) {
if (line[len - 1] != '\n') {
tot = tot + len;
}
if (line[1] == '\n' || line[0] == '\n') {
printf("%d\n", tot + 1);
text_l = text_l + (tot + 1);
tot = 0;
}
}
printf("%d\n", text_l);
}
The idea is to set the max lenght of the string considered for the array line
ad 2.
For a string as abcdef\n
, the array line
will be ab
. Since the last element of the array is not \n
(thus the line we are considering is not over), we save the length up until now and repeat the cycle. We will get then the array made of cd
, then ef
and at the end we will get the array of just \n
. Then the else if
condition is executed, since the first element of this array is\n
, and we print the tot
length obtained from the previous additions. We add +1 in order to also consider the new character \n
. This works also for odd strings: with abcdefg\n
the process will go on up until we reach g\n
and the sum is done correctly.
Outside the loop then we print the total amount of text.
Is this a correct way to do the exercise?
Upvotes: 0
Views: 152
Reputation: 224032
The exercise says to “Revise the main routine,” but you altered the definition of MAXLINE
, which is outside of main
, so that is not a valid solution.
Also, your code does not have the copy
or getline
routines of the original. Your get_line1
appears to be identical except for the name. However, a correction solution would use identical source code except for the code inside main
.
Additionally, the exercise says to print “as much as possible of the text.” That is unclearly stated, but I expect it means to keep a buffer of MAXLINE
characters (with MAXLINE
at its original value of 1000) and use it to print the first MAXLINE
−1 characters of the longest line.
Upvotes: 2