fscanf problem

Dec 29, 2010 at 11:27pm
Hi everyone. I got a problem with, i suppose fscanf. I need to read strings from a .txt file, line by line, a total of 200 lines. But it seems that fscanf can read only up to 30 lines, after that, it stops working, and offers Debug or Close...
Here's the code...

FILE* f;

f=fopen("D:\\data.txt","r");

...............

for(int i=1;i<=velbaze;i++){
fscanf(f,"%s",&pojmovi[i]);
printf("%s\n",pojmovi[i]);


};

where velbaze is 200.

What could be the problem?

Tnx in advance,
Nenad.
Dec 29, 2010 at 11:42pm
What is pojmovi? How is it declared?
Dec 30, 2010 at 12:47am
If you are reading lines of text, you should skip fscanf() altogether and use fgets():
http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

If you must use fscanf(), make sure you put an upper limit on the number of characters to store using a width specifier. Make sure to read the docs:
http://linux.die.net/man/3/scanf
Note, in particular, that the width does not include space needed to store the terminating '\0'.

1
2
char s[ 50 ];
fgets( s, 50, f );  // reads an entire line, including the newline character 
1
2
char s[ 50 ];
fscanf( f, "%49s", s ); // discards leading whitespace, stops on whitespace 
1
2
char s[ 50 ];
fscanf( f, "%49[^\n]\n", s ); // like fgets(), but does not store the newline character 

Hope this helps.
Last edited on Dec 30, 2010 at 12:48am
Dec 30, 2010 at 8:02am
Pojmovi is declared as:

char pojmovi[40][1000]

I tried fgets(), the same exact problem, after 30. string it stops working....

Tnx for the effort.
Dec 30, 2010 at 8:35am
Considering that as Duoas said, fscanf does not read lines with the %s specifier, but instead words, and that fgets reads lines, it probably indicates that the IO is not the problem. I mean you should have gotten the error at different loop iterations, unless each line of your input file contains exactly one word.
Last edited on Dec 30, 2010 at 8:35am
Dec 30, 2010 at 1:12pm
OMG, i missdeclared pojmovi[]...

It should have been char pojmovi[1000][40]. Question closed, Thank yoe, everyone.
Topic archived. No new replies allowed.