I have this program in C I wrote that reads a file line by line (each line has just one word), sorts the alphabets, and then displays the sorted word and the original word in each line.
#include<stdio.h>
int main()
{
char line[128];
int i=0;
int j;
int length;
while(fgets(line,sizeof line,stdin) != NULL)
{
char word[128];
for (i=0; line[i] != '\0'; i++)
{
word[i]=line[i];
}
while (line[i] != '\0')
i++;
length=i;
for (i=length-1; i >=0; i--)
{
for (j=0; j<i; j++)
{
if (line[j] > line[i])
{
char temp;
temp = line[j];
line[j] = line[i];
line[i]=temp;
}
}
}
printf("%s %s",line,word);
}
return 0;
}
I'm compiling and running it using the following bash commands.
gcc -o sign sign.c
./sign < sample_file | sort > output
The original file (sample_file) looks like this:
computer
test
file
stack
overflow
The output file is this:
ackst stack
cemoprtu computer
efil file
efloorvw overflow
er
estt test
ter
ter
I'm having two issues:
- The output file has a bunch of newline characters at the beginning (ie. about 5-7 blank lines before the actual text begins)
- Why does it print 'ter' twice at the end?
PS - I know these are very elementary questions, but I only just started working with C / bash for a class and I'm not sure where I am going wrong.