title: How to print a numerical matrix into a string in C?
body: <p>Suppose we have a matrix in C (a 2D array).</p>
  
  <p>I wonder how could I print the matrix into a string in C.</p>
  
  <p>For example, if I have</p>
  
  <pre><code>double M[2][2]={{1.2,3.4},{3.14,2.718}}
  </code></pre>
  
  <p>I want to get a string like this:</p>
  
  <pre><code>"1.200  3.400\n3.140  2.718"
  </code></pre>
  
  <p>which could be printed as</p>
  
  <pre><code>1.200 3.400
  3.140 2.718
  </code></pre>
  
  <p>If print to screen, the problem will become easier because we need not consider the buffer size. However, when printing to a string, it seems hard to know how large the string buffer should be, if I want to use functions like 'sprintf'.</p>
  
  <p>I searched google and stackoverflow but almost all of what I get is about how to convert string to numerical...</p>
  
  <p>How to do this in C? Are there any libs?</p>
  
  <p>Could you please help? Thank you!</p>
  
  <p>EDIT:
  The 'snprintf' solution works well for the situation of just one number.
  But for matrix, it is supposed to use loops to go through every element.
  And then add a little to the string in each loop. Will this work with 'snprintf'?</p>