I have recently started coding in language C and I was trying to do a question from a C programming book. The question was to print all lines that are longer than a specified length.
What I've done is take a line one by one and if the len>20 I append the line at the end of longest[] to get one final array that will store all the lines and will print the lines one by one.This is what I've achieved so far -->
#include <stdio.h>
#define LIMIT 2000
#define MAX 500
int getLine(char line[], int limit);
void copy(char line[], char longest[]);
int main()
{
//Print lines>20 characters among other lines.
int len,final=0;
char line[MAX], longest[LIMIT];
while((len=getLine(line,MAX)) > 0)
{
if(len>20)
{
copy(line,longest);
}
}
while(longest[final] != '\0')
{
printf("%c",longest[final])
++final;
}
return 0;
}
int getLine(char line[], int limit)
{
int ch, i=0;
while(i<limit-1 && (ch=getchar())!=EOF && ch!='\n')
{
line[i]=ch;
++i;
}
if(ch=='\n')
{
line[i]=ch;
++i;
}
line[i]='\0';
return i;
}
void copy(char line[], char longest[])
{
int i=0;
while(longest[i] != '\0' && i<LIMIT-1)
++i;
int k=0;
while(longest[i]=line[k] != '\0' && i<LIMIT-1)
{
++i;
++k;
}
longest[i]='\0';
}
The issue I am facing is that when I am trying to print the final longest[] array which should be storing all the lines that are > 20 in length the final output is something like
LINES > 20 : M�[����ý
Any help would be appreciated, Thank you! :)