Originally Posted by
theonetruehero
Hey all. Tasked with creating a program that will take words from a file, alphabetize them, and write them to an output file.
i.e.
Bananas
Apples
Falcon
Should become:
Apples
Bananas
Falcon
I've got code that should theoretically work under the guidelines I've been given, and it arranges the values in some order, just not alphabetical. Thusly, I am confused.
*EDIT*
Haha matsp. I wouldn't call it unreadable but It's been a while. And I'm working with my younger cousin, who is currently taking C. I'm trying to give him a hand. Anyways, we'll rewrite the code to make it more manageable.
It is unreadable. Not in the sense that it is impossible to comprehend, but in the sense that it's too ugly to be bothered with.
FYI this:
Code:
++n; fscanf(fp,"%[^\n]%*c",t);
sp=n==1?(char *)malloc(sizeof(char *)):realloc(sp,(n)*sizeof(char *))
Should look something like:
Code:
{ // Random bracket to emphasize the importance of indentation.
++n;
// Read characters until newline
fscanf(fp, "%[^\n]%*c", t);
// Malloc data depending on the value of n.
sp = (n==1) ? (char*)malloc(sizeof(char *)) : realloc(sp, n * sizeof(char *))
}
Comments are mandatory - especially with such cryptic code. The ones I wrote were just examples.
Code in red needs to be removed / changed - here are the items in order of appearance:
- %*c ignores a character. If you're reading up to a newline, the character after that hardly needs to be ignored as it wouldn't be read in the first place?
- Don't cast malloc
- You don't want to allocate char pointers, but chars.