Today I encountered a problem with scanf functions. Assume that you have a structure like the following example.
struct structA{
bool bVal;
int nVal;
}
If you run the following code
structA a;
a.nVal = 7;
...// Assume that we read a text file and the only text is "0"
fscanf(fp,"%d",&a.bVal);
printf("\n a.bVal=%d",a.bVal);
printf("\n a.nVal=%d",a.nVal);
It will print
a.bVal = 0
a.nVal = 0
The reason is that the fscanf function assumes a.bVal is an integer and overwrites the a.nVal first 3 bytes. This problem can be solved by the following dirty solution.
structA a;
a.nVal = 7;
...// Assume that we read a text file and the only text is "0"
int nBVAL;
fscanf(fp,"%d",&nBVAL);
a.bVal = nBVAL;
printf("\n a.bVal=%d",a.bVal);
printf("\n a.nVal=%d",a.nVal);
My question is that is there a cleaner and straightforward way of avoiding this problem beside the solution explained?