Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting array to file code does not work (C++)
    text
    copied!<p><strong>UPDATE: If anyone is reading this and having a similar problem, it seems that the problem was where I converted a double to an int. Where I thought for example 54 was stored as 54.000..., it was actually stored as 53.99999... and when changing to int, it became 53. A workaround to this problem which I found out is to simply add 0.5 and so the code that was</strong></p> <pre><code>int output_buffer=O[m][n]; </code></pre> <p><strong>becomes</strong></p> <pre><code>int output_buffer=O[m][n]+0.5; </code></pre> <hr> <p>I have a two dimensional array of doubles called "O". Where </p> <pre><code>double O[3][3]; </code></pre> <p>I use these two functions right after the other in this exact order;</p> <pre><code>... displaymatrixO(); writedecrypted(); ... </code></pre> <p>Where </p> <pre><code>int displaymatrixO() { cout &lt;&lt; "O is:" &lt;&lt; "\n"; for (int n=0;n&lt;3;n++) for (int m=0;m&lt;3;m++) { cout &lt;&lt; O[m][n]; if (m == 2) cout &lt;&lt; "\n"; else cout &lt;&lt; " "; } } </code></pre> <p>And </p> <pre><code>int writedecrypted() { for (int n=0;n&lt;3;n++) for (int m=0;m&lt;3;m++) { int output_buffer=O[m][n]; fputc (output_buffer,opFile); } } </code></pre> <p>Where</p> <pre><code>FILE *opFile; opFile=fopen ("decrypted.txt","wb"); ... </code></pre> <p>When the program is run, the first function (displaymatrixO) outputs the matrix O to screen in this fashion:</p> <pre><code>O is: 49 50 51 52 53 54 3 3 3 </code></pre> <p>Which is correct, this is what O is supposed to be. </p> <p>The second function then is supposed to typecast and write the individual values of the matrix to a file where each value takes up the space of 8 bits/ 1 byte. When I use a hex editor and look at the file, this is what the file looks like(in hex):</p> <pre><code>0x31 0x32 0x33 0x33 0x35 0x35 0x03 0x03 0x03 </code></pre> <p>In 8-bit signed integer format (i.e. how O is displayed using displaymatrixO), this is what it looks like:</p> <pre><code>49 50 51 51 53 53 3 3 3 </code></pre> <p>i.e. </p> <pre><code>49 50 51 51 53 53 3 3 3 </code></pre> <p>It seems to copy O[2][0] onto O[0][1] and O[1][1] onto O[2][1]. I have looked at the code again and again and I can't seem to figure out where I am going wrong! Help if you can...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload