Ahmad Gaffoor
Ahmad Gaffoor

Reputation: 103

fscanf not working as expected.

I have a word file with 3 words. I need to read each word into an array. I tried doing this with fscanf(), but it doesn't work. What am I doing incorrectly?

#include <stdio.h>

void main(){
    char words_array[80];
    FILE *dictionary;
    dictionary = fopen("dictionary.txt", "r");
    fscanf (dictionary, "%s", words_array);
    printf("The content of words_array is: %s, %s, %s, \n", words_array[0], words_array[1], words_array[2]);
}

I get the following error when I try to compile:

warning: format '%s' expects argument of type '* char' but argument has type 'int'

The dictionary.txt file is as follows:

apple
orange
bananna

Thanks all!

Upvotes: 0

Views: 3630

Answers (3)

KevinDTimm
KevinDTimm

Reputation: 14376

Your variable words_array has space for 80 characters. You're mistakenly thinking you have 80 words. The printf line to print the first word is:

printf("The content of words_array is: %s\n", words_array);

If you want to print all the lines/words, you'll need to wrap this in a reader of the lines of the file:

while (fscanf (dictionary, "%s", words_array)) {
        printf("%s \n", words_array);
    }

read the man page for fscanf to see why.

[edit]

instead of the while loop:

char words_array[3][80];
for (int i = 0; i < 3; i++)
   fscanf(dictionary, "%s", words_array[i]);

[/edit]

Upvotes: 1

Sangeeth Saravanaraj
Sangeeth Saravanaraj

Reputation: 16597

Assuming you have only one word (fruit) in one line (and < 80 characters long) in the dictionary.txt, the following should work!

#include <stdio.h>

int main(void)
{
    char words_array[80];
    FILE *dictionary;
    dictionary = fopen("dictionary.txt", "r");
    while (fscanf (dictionary, "%s", words_array) == 1) {
        printf("%s \n", words_array);
    }

    return 0;
}

Output:

$ gcc fsca.c 
$ ./a.out 
apple 
orange 
bananna 
$ cat fsca.c 

Adding an alternative answer as per request from the OP author.

#include <stdio.h>

int main(void)
{
    char word1[80], word2[80], word3[80];
    FILE *dictionary;
    dictionary = fopen("dictionary.txt", "r");
    fscanf(dictionary, "%s", word1);
    fscanf(dictionary, "%s", word2);
    fscanf(dictionary, "%s", word3);
    printf("%s %s %s\n", word1, word2, word3);

    return 0;
}

Output

$ gcc fsca.c 
$ ./a.out 
apple orange bananna
$ 

Upvotes: 2

Hari
Hari

Reputation: 5227

char words_array[80] is merely a character array - NOT an array of strings.

So when you try to print out words_array[0] and so on, they are characters and hence a mismatch with %s.

Also you would want to use feof for reading till the end of file. Just use fscanf till end of file is reached, read a string and print it out.

Upvotes: 1

Related Questions