patterncMinor
Exercise 1-22 from K and R: line folding
Viewed 0 times
lineexercisefoldingandfrom
Problem
I'm currently learning C with K&R, i'm right now in the exercise 1-22, but it's a little... hard to understand (at least for me). It says:
Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long line, and if there are no blanks or tabs before the specified column.
I've done this:
Does this matches with the exercise?
Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long line, and if there are no blanks or tabs before the specified column.
I've done this:
#include
void seccionar(char to[], char from[])
{
int a = 0,b = 0, i = 0;
int max = 0;
while(from[i] != '\0'){
if(max 1){
seccionar(to, from);
printf("%s", to);}
return 0;
}Does this matches with the exercise?
Solution
Potential Buffer Overflows
You've defined
Formatting
Your indentation is inconsistent and in places seems rather excessive.
Variable names
Many of your variable names could use some work. Names like
Inefficiency
Depending on your viewpoint, there's a fair argument to be made that your code is less efficient than there's any real need for. In particular, it works by reading data into one buffer, then copying all that data to another buffer.
I'd consider a strategy something on this general order:
You've defined
from and to to hold only 10 characters apiece, but none of the code actually enforces that, and it appears that you plan on them holding 80 characters or so. You should probably pass the array size to getline, for example, so that it can stop reading either when it reaches a new-line or when it runs out of space in the destination buffer.Formatting
Your indentation is inconsistent and in places seems rather excessive.
Variable names
Many of your variable names could use some work. Names like
a, b and max (that doesn't seem to hold a maximum) could be replaced with much more meaningful names.Inefficiency
Depending on your viewpoint, there's a fair argument to be made that your code is less efficient than there's any real need for. In particular, it works by reading data into one buffer, then copying all that data to another buffer.
I'd consider a strategy something on this general order:
- Read in a line
- If it's shorter than the maximum, print it out and go back to 1
- Starting from
line[max_width], search backward in the string to find a space.
- Change that space to a new-line.
- Repeat from 2, using the string following the newline you just inserted.
Context
StackExchange Code Review Q#129381, answer score: 4
Revisions (0)
No revisions yet.