I debugged a function and it is working. So yay, teaching myself C seems to be going along well. But I want to make it better. That is, it reads a file like this:
want
to
program
better
And puts each individual line of string into an array of strings. Things get weird when I print things out however. As far as I read, strcpy() should just copy a string until the \0 character. If that is true, why is the following printing the string want and \n? It is like strcpy() also copied \n and it is hanging in there. I want to get rid of that.
My code for copying the file is below. I didn't include the entire program because I don't believe that is relevant for what is happening. I know the problem is in here.
void readFile(char *array[5049])
{
char line[256]; //This is to to grab each string in the file and put it in a line.
int z = 0; //Indice for the array
FILE *file;
file = fopen("words.txt","r");
//Check to make sure file can open
if(file == NULL)
{
printf("Error: File does not open.");
exit(1);
}
//Otherwise, read file into array
else
{
while(!feof(file))//The file will loop until end of file
{
if((fgets(line,256,file))!= NULL)//If the line isn't empty
{
array[z] = malloc(strlen(line) + 1);
strcpy(array[z],line);
z++;
}
}
}
fclose(file);
}
So now, when I do the following:
int randomNum = rand() % 5049 + 1;
char *ranWord = words[randomNum];
int size = strlen(ranWord) - 1;
printf("%s",ranWord);
printf("%d\n",size);
int i;
for(i = 0; i < size; i++)
{
printf("%c\n", ranWord[i]);
}
It prints out:
these
6
t
h
e
s
e
Shouldn't it be printing out the following instead?
these6
t
h
e
s
e
So the only thing I can figure is that when I put the strings into an array, it put the \n in there too. How can I get rid of that?
As always, with respect. GeekyOmega