c++.command-line - strange fscanf/console output problem
- Jens Friese (67/67) Oct 01 2003 Hi,
- Walter (1/1) Oct 01 2003 Try reading/writing the file in binary, use "wb+" and "rb+".
Hi,
please have a look at my problem:
I want to save random combinations of zeros and ones to a file.
[..]
// GENERATION OF RANDOM 0-1-COMBINATIONS
long int seed = time(0);
TRanrotWGenerator rg(seed);
data = fopen("strategies.txt", "w+");
for (i=0;i<h;i++) {
for (j=0;j<10;j++) {
indiv[i].strategy1[j]=(int)round(rg.Random()); //random
fprintf(data,"%d\n",indiv[i].strategy1[j]); //saving
indiv[i].strategy2[j]=(int)round(rg.Random()); //random
fprintf(data,"%d\n",indiv[i].strategy2[j]); //saving
}
}
fclose(data);
[..]
This works fine.
// CONCOLE OUTPUT IS CORRECT
0 > |0110011101| & |0101011011|
1 > |0001111011| & |1001101111|
2 > |1000000101| & |0111010000|
3 > |1010001110| & |0000111000|
4 > |1011000001| & |1011010011|
5 > |0110110000| & |1101111110|
6 > |0010110010| & |0010101011|
7 > |1111100011| & |0111000001|
8 > |0101000111| & |0100111000|
9 > |0101110111| & |1100000110|
Now I open the file again.
data = fopen("strategies.txt", "r+");
for (i=0;i<h;i++) {
for (j=0;j<10;j++) {
fscanf(data,"%d\n",&indiv[i].strategy1[j]);
fscanf(data,"%d\n",&indiv[i].strategy2[j]);
HERE IS THE PROBLEM:
THE FIRST STRATEGY IS READ CORRECTLY BUT THE
FIRST THREE CHARS OF THE SECOND STRATEGY ARE
ALLWAYS ZERO!!
TO ADD TO THE CONFUSION:
I KNOW THAT INSIDE THIS LOOP, THE VALUES OF
BOTH STRATEGIES ARE CORRECT. BUT ONCE I CLOSE
THE FILE, PART OF THE INFORMATION VANISHES???!!!???
}
}
fclose(data);
VVVVVVV
VVVVV
VVV
0 > |0110011101| & |0001011011|
1 > |0001111011| & |0001101111|
2 > |1000000101| & |0001010000|
3 > |1010001110| & |0000111000|
4 > |1011000001| & |0001010011|
5 > |0110110000| & |0001111110|
6 > |0010110010| & |0000101011|
7 > |1111100011| & |0001000001|
8 > |0101000111| & |0000111000|
9 > |0101110111| & |0000000110|
I would REALLY appreciate your help.
Have a great day
Jens
Oct 01 2003
Try reading/writing the file in binary, use "wb+" and "rb+".
Oct 01 2003








"Walter" <walter digitalmars.com>