Hello all, so my program is suppose to take in an input and every 5 characters make a new line for the next maximum of 5 characters. It seems like its copying correctly but everytime it copies an input that is able to be split up into 5 characters perfectly, it adds an additional empty line. Other odd lines of input work fine though. I think it has something to do with how I am setting to[i] to be a new line. However I am unsure of how to fix it.
Code:
#include <stdio.h>
#define MAXLINE 1000
#define FOLD 5
int getline(char line[]);
void copy(char to[], char from[]);
//folds any given length input into
//lines of 5 characters
main(){
int len; //current line length
char unfolded[MAXLINE]; //current input line
char folded[MAXLINE]; //folded line saved here
len = 0;
while ((len = getline(unfolded)) > 0){
copy(folded, unfolded);
printf("%s", folded);
}
return 0;
}
//read a line into s, return length
int getline(char s[]){
int c, i;
for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
//copy from into to: assume to is big enough
//the folding copy
void copy(char to[], char from[]){
int i, i2, foldnum;
i = 0;
i2 = 0;
foldnum = 0;
while (from[i2] != '\0'){
//while foldnum is not equal to FOLD
//copy normally
//increment foldnum by 1
if(foldnum != FOLD){
to[i] = from[i2];
i++;
i2++;
++foldnum;
}
//when foldnum is equal to FOLD
//make a new line
//reset foldnum
//increase i by 1
else if (foldnum == FOLD){
to[i] = '\n';
foldnum = 0;
++i;
}
}
to[i] = '\0';
}