I'm having a bit of an issue with my solution to Euler problem 22. I have a list of names that are surrounded by quotation makes and separated by commas (I.E. "MARY",). I have created a function (called format) which removes the quotation marks and commas and builds a new array with the names, delimiting them with line feeds (I.E. MARY\n). When I try printing this list with puts(), I get a formatted list as expected, but at the end all of the unformatted names also appear. Obviously, I would like to have only the formatted list returned. If anybody could offer some advice, I would be obliged.
Code:
/* Project Euler problem 22
*
* http://projecteuler.net/problem=22
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_NAMES 6000
void alpha_sort(char *buff)
{
const char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *p;
int i;
// array of char pointers
char *names[MAX_NAMES];
/*names[0] = "test";*/
/*p = names[0];*/
/*printf("%c\n", p[0]);*/
}
char *format(char *buff)
{
int i = 1, j = 0;
char *p;
p = malloc(sizeof(buff));
while(buff[i] != '\0')
{
if(isalpha(buff[i]))
{
p[j] = buff[i];
j++;
i++;
}
else
{
p[j] = '\n';
j++;
do
{
i++;
} while ( (isalpha(buff[i]) == 0) && (buff[i] != '\0') );
}
}
free(buff);
return p;
}
char *rfile(void)
{
long size = 0;
FILE *fp;
fp = fopen("names.txt", "r");
fseek(fp, 0, SEEK_END);
size = ftell(fp);
// allocate memory size of file
char *buff = (char*) malloc(sizeof(char) * size);
rewind(fp);
fread(buff, 1, size, fp);
fclose(fp);
return buff;
}
int main(void)
{
char *p = format(rfile());
puts(p);
alpha_sort(p);
return 0;
}