Reputation: 183
I just figured out how to do this with integers so decided to give it a go with strings and got stuck.
Here is what is in my file "kw":
keyword0
keyword1
keyword2
keyword3
With this current code I'm getting "error: format '%s' expects argument of type 'char *', but argument 3 has type 'char **'
#include <stdio.h>
int main () {
FILE *pFile;
pFile = fopen("kw", "r");
if (pFile != NULL) {
char *a[3];
int i;
for(i = 0; i <= 3; i++) {
fscanf(pFile, "%s", &a[i]);
printf("%s\n", a[i]);
}
}
return 0;
}
Could someone point me in the right direction here? Thank you.
Upvotes: 2
Views: 1249
Reputation: 726599
There are several problems with this code:
a
, while the array has only three elements.scanf
.To fix the first problem, change <=
for !=
or <
, like this:
for(i = 0; i != 3; i++)
To fix the second and the third problem, use malloc
:
a[i] = malloc(21*sizeof(char));
fscanf(pFile, "%20s", a[i]);
Once you are done with the data that you allocated, don't forget to free the strings:
for(i = 0; i != 3; i++) {
free(a[i]);
}
Upvotes: 2