user1455112
user1455112

Reputation: 183

Read lines of file, put each line into an array, then print

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

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

There are several problems with this code:

  • You are going through four elements of the array a, while the array has only three elements.
  • You did not allocate space for the strings that you are reading with scanf.
  • You do not pass the address of address when you read strings.

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

Related Questions