Using fscanf to set a variable in a different class
I'm trying to read a number from a file and set it to a public variable in a different class. The function that is reading the file has a pointer-object instance of that class. I'm facing a weird issue:
The following works:
int dummy;
fscanf(file,"%d",&dummy); // assume the file stores the number 10
globals->var = dummy;
cout << "variable is " << globals->var << endl; // this outputs 10 to console. great!
But I'm going to have a lot of fscanf
's to do, and I don't want to create all of these redundant dummy
variables. I tried the following:
fscanf(file,"%d",&globals->var);
cout << "variable is " << globals->var << endl; // this outputs 2.9e-321 (aka junk)
Is there a reason that doesn't work? Do I need to do it like globals->&var
, or some variation like that? I tried to wrap it in parentheses like so: &(globals->var)
, but that didn't work either. Is there a reason this is not working (without me having to paste many many many lines of开发者_开发百科 code)
Thanks!
As you said in the comment, the type of var
is double. Yes, that is the problem. You should use %f
for it.
Apart from that, I would give you a piece of advice:
Prefer using C++ stream for I/O work. They're type-safe. If you use them, you would not face this problem which you faced it with fprintf
.
Here is how you should use it:
std::ifstream file("filename.txt");
file >> globals->var; //don't worry about whether var is int, or double!
Cool, isn't it?
The Problem is most probably that globals->var is a float
or double
convert it to an int
or some other integer-type and it should work
The reason why it's outputting "junk" is that float
/double
numbers are encoded in a special way. If you just overwrite that memory with an perfectly valid integer like:
double value = 0.0;
*((int*)&value) = 42;
// value is now something like 2.07508e-322
you nonetheless get a "strange" number. This is what happens internally in scanf with %d as parameter.
精彩评论