开发者

Reading in values from a file - some are correct, others are incorrect

I need to read in values for three variables from a file, which are then used to perform calculations. The values are listed in a specific format. For example, these are the contents of one such file:

2  //number of items per variable
0 0 0  //values for center locations (stored as struct)
0 0 .5
10  //values for some variable v1 (type double)
5
-10  //values for some variable v2 (type double)
10

This is the code I have for reading in these values:

 ...
 fscanf(file, "%d\n", &nItems);
 for (unsigned int i = 0; i < nItems; i++)
 {
  float cx, cy, cz;
  fscanf(file, "%f %f %f\n", &cx, &cy, &cz);

  center[i].cx = cx;
  center[i].cy = cy;
  center[i].cz = cz;
 }
 for (unsigned int i = 0; i < nItems; i++)
 {    
  fscanf(file, "%f\n", &v1[i]);   
 }  
 for (unsigned int i = 0; i < nItems; i++)
 {
  fscanf(file, "%f\n", &v2[i]);   
 }

The problem I'm facing is that when I read in the values this way and output them, the values for nItems and the center locations are correct, but the rest are incorrect. However, the signs开发者_StackOverflow and relative magnitude of those values are correct. For example, for the list of values shown above, these are the outputted values:

Correct              Outputted values
2                    2  
0 0 0                0.000000 0.000000 0.000000  
0 0 .5               0.000000 0.000000 0.500000
10                   524288.000000  
5                    2048.000000
-10                  -524288.000000  
10                   524288.000000

I don't know why the values for the last two variables are being read in incorrectly. I would appreciate your advice.

Thanks.


I'm not sure this is it, but from your example file it looked like second two groups of data are integers rather than floating-point values. In your code, though, you're writing

for (unsigned int i = 0; i < nItems; i++)
{    
    fscanf(file, "%f\n", &v1[i]);   
} 

That is, you're reading them using the %f specifier, which is for floats. If the v1 and v2 arrays are arrays of ints, this won't work correctly; it will overwrite the integers with bit patterns that are meant to be interpreted as floats.

To fix this, try writing this instead:

for (unsigned int i = 0; i < nItems; i++)
{    
    fscanf(file, "%d\n", &v1[i]);   
} 

That is, use the %d specifier.

Again, this may be totally off since I can't see more of the code, but if I had to guess this is where I'd put my money. Let me know if this is incorrect and I can remove this post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜