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
varis double. Yes, that is the problem. You should use%ffor 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:
Cool, isn’t it?