Jump to content
  • Advertisement
Sign in to follow this  
DJ14IVI3

A quick question regarding fscanf()

This topic is 4428 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm making a game and I'm storing some stats in a text file (not a good habit, I know, but I've yet to learn databases). The text file consist of 128 lines of 26 numbers each, separated by spaces. How would I go about loading these numbers? I've tried it like this:
for(i=0;i<128;i++)
    {
       fscanf(fp,"%d %d",&itemlist.composition.reversible,&itemlist.composition.time);
       for(j=0;j<8;j++) fscanf(fp,"%d %d %d",&itemlist.composition.ingredients[j][0],&itemlist.composition.ingredients[j][1],&itemlist.composition.ingredients[j][2]);
    }
but it doesen't seem to work. And putting it all in a single fscanf() would be way too messy. Any suggestion? Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
Can I offer an idea, try putting the data in to XML. It is better organized, pretty fast and saves a lot of trouble in the end.

theTroll

Share this post


Link to post
Share on other sites
Please, please, please don't rush off to use some other format like XML or a database. Text files are perfectly fine, and are very easy to process. For simple data there's no need to go off and overcomplicate your program by adding in massive XML or database libraries.

Try this:


for(i = 0; i < 128; ++i)
{
fscanf(fp, "%d", &itemlist.composition.reversible);
fscanf(fp, "%d", &itemlist.composition.time);

for(j = 0; j < 8; ++j)
{
for(k = 0; k < 3; ++k)
fscanf(fp, "%d", &itemlist.ingredients[j][k]);
}
}



This makes things a little more lenient. When you specify a string like "%d %d %d" to fscanf(), it will usually try to find that exact pattern (three integers separated by spaces) which might not be how your file is laid out. Also note that fscanf() doesn't understand optional data, so if it doesn't see the precise number of fields it expects, you'll get bogus results.

Note that this still expects that every field you read is an int in the struct/class - if that is not the case, you'll need to tell fscanf() to read some other type of data ("%d" indicates an integer).

If that doesn't take care of your problem, feel free to post some additional details (i.e. what your data file looks like, the results you expect after loading the file, and the actual results) and we'll have a look at it from there.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!