{"id":3992,"date":"2018-09-09T20:36:11","date_gmt":"2018-09-09T18:36:11","guid":{"rendered":"https:\/\/blue.pri.ee\/ttu\/?page_id=3992"},"modified":"2025-06-20T20:53:04","modified_gmt":"2025-06-20T18:53:04","slug":"some-printf-tips","status":"publish","type":"page","link":"https:\/\/blue.pri.ee\/ttu\/coding-guides\/some-printf-tips\/","title":{"rendered":"Using printf with tips and tricks"},"content":{"rendered":"<p>The following page will list various tips and tricks on using the printf() function. I recommend copying those examples and trying them out for yourself. I also encourage You to try modify some lines or values and see what happens.<\/p>\n<p>Every code example has some accompanying text, explaining what the good and bad sides of things might be. There are also some recommendations and alternative solutions provided to improve even further.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/blue.pri.ee\/ttu\/coding-guides\/some-printf-tips\/#Printing_text\" >Printing text<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/blue.pri.ee\/ttu\/coding-guides\/some-printf-tips\/#Printing_values_from_variables\" >Printing values from variables<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/blue.pri.ee\/ttu\/coding-guides\/some-printf-tips\/#Padding_and_aligning\" >Padding and aligning<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/blue.pri.ee\/ttu\/coding-guides\/some-printf-tips\/#Useful_tricks\" >Useful tricks<\/a><\/li><\/ul><\/nav><\/div>\n<h3><span class=\"ez-toc-section\" id=\"Printing_text\"><\/span>Printing text<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<pre class=\"toolbar:1 lang:c decode:true\" title=\"Sample 1\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    printf(\"Hello!\");\r\n    printf(\"How are you?\");\r\n    return 0;\r\n}<\/pre>\n<p>printf() function doesn&#8217;t automatically include a line change. Newline characters must be added manually using a special escaped character \\n. An alternative would be to use the function puts().<\/p>\n<pre class=\"toolbar:1 lang:c decode:true\" title=\"Sample 2\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    printf(\"Hello!\\n\");\r\n    printf(\"How are you?\\n\");\r\n    return 0;\r\n}\r\n<\/pre>\n<p>It&#8217;s also important to add a newline character to the last line printed line of the program. It this is not done, it might cause a lot of confusion when the program started from the command line.<\/p>\n<pre class=\"toolbar:1 lang:c decode:true\" title=\"Sample 3\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    printf(\"Hello!\\nHow are you?\\n\");\r\n    return 0;\r\n}\r\n<\/pre>\n<p>You can also add multiple newline characters within one function call.<\/p>\n<pre class=\"toolbar:1 lang:c decode:true\" title=\"Sample 4\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    puts(\"Hello!\");\r\n    puts(\"How are you?\");\r\n    return 0;\r\n}\r\n<\/pre>\n<p>An alternative was to use the function puts(). This function is special in a way that it&#8217;s only meant to print plain text without any kind of formatting. This means that you are not able to print variable values with this either. However you do get automatic line change.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Printing_values_from_variables\"><\/span>Printing values from variables<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To print values in C, we only need to know the data type of the variable, the variable&#8217;s name and where do we intend to place this value. In a sense, it&#8217;s quite a basic operation.<\/p>\n<pre class=\"toolbar:1 lang:c decode:true\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    char name[] = \"Dolores\";\r\n    int number = 21;\r\n    printf(\"%s! You're number %d on the waiting list\\n\", name, number);\r\n    return 0;\r\n}\r\n<\/pre>\n<p>As a first example, we&#8217;ll print two values from two different types of variables. It&#8217;s important to make sure that we use the correct format (%d for integer, %s for string) and that the variables are correctly ordered after the format. The values from the variables are placed into the text from left to right (in the order of appearance). When an invalid format for the variable is used, a compiler warning is given. This means that it will still compile, however the result might be unexpected.<\/p>\n<pre class=\"lang:c decode:true\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    float value = 3.33f;\r\n    printf(\"The value is %f\\n\", value);\r\n    printf(\"The value with limited precision is %.2f\\n\", value);\r\n    return 0;\r\n}\r\n<\/pre>\n<p>A more difficult situation comes from real numbers. It&#8217;s often advisable to limit the number of places after the comma, so not to panic the user and make the output pleasing.<\/p>\n<pre class=\"lang:c decode:true\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    float value = 994.331f;\r\n    printf(\"The value is %f\\n\", value);\r\n    return 0;\r\n}<\/pre>\n<p><a href=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/round.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-3944 aligncenter\" src=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/round.png\" alt=\"\" width=\"283\" height=\"21\" \/><\/a><\/p>\n<p>You must also be careful with how much precision a variable can hold. It is not possible to represent all real numbers in a digital form without some loss.\u00a0 This is due to the binary storage methods that we use with computers. One of the ways to get around this would be to use a data type with more precision (e.g. double) or even storing floating point numbers as integers and converting as necessary. The latter is actually how banks often do it.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Padding_and_aligning\"><\/span>Padding and aligning<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>There are often scenarios where just printing a value within a line of text will not be enough. This is often the case with displaying tables where aligning fields becomes necessary.<\/p>\n<pre class=\"lang:c decode:true\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    char *names[] = {\"Ott\", \"Dolores\", \"Madis\"};\r\n    int employeeNum[] = {7, 19, 2123};\r\n    int ages[] = {22, 19, 53};\r\n\r\n    for (int i = 0; i &lt; 3; i++)\r\n    {\r\n        printf(\"%s\\t%d\\t%d\\n\", names[i], ages[i], employeeNum[i]);\r\n    }\r\n    return 0;\r\n}\r\n<\/pre>\n<p>The most primitive way to do this is using the tabular or \\t within the code. This will align the fields to some predesignated tab stops within the terminal itself.<\/p>\n<p><a href=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab1-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3948 size-full\" src=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab1-1.png\" alt=\"\" width=\"263\" height=\"54\" \/><\/a><\/p>\n<pre class=\"lang:c decode:true\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    char *names[] = {\"Ott\", \"Dolores\", \"Johanna-Maria\"};\r\n    int employeeNum[] = {7, 19, 2123};\r\n    int ages[] = {22, 19, 53};\r\n\r\n    for (int i = 0; i &lt; 3; i++)\r\n    {\r\n        printf(\"%s\\t%d\\t%d\\n\", names[i], ages[i], employeeNum[i]);\r\n    }\r\n    return 0;\r\n}\r\n<\/pre>\n<p><a href=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3949\" src=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab2.png\" alt=\"\" width=\"354\" height=\"54\" srcset=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab2.png 354w, https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab2-300x46.png 300w\" sizes=\"auto, (max-width: 354px) 100vw, 354px\" \/><\/a><\/p>\n<p>However as soon as the length of the field starts to differ enough so that they go to different tab stops, everything breaks. Those tab stops are usually read from the left and the length of one is 4 characters.<\/p>\n<pre class=\"lang:c decode:true\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    char *names[] = {\"Ott\", \"Dolores\", \"Johanna-Maria\"};\r\n    int employeeNum[] = {7, 19, 2123};\r\n    int ages[] = {22, 19, 53};\r\n    float wages[] = {13f, 8.95f, 10.1f};\r\n\r\n    for (int i = 0; i &lt; 3; i++)\r\n    {\r\n        printf(\"%-13s  %3d  %06d  %5.2f\\n\", names[i], ages[i], employeeNum[i], wages[i]);\r\n    }\r\n    return 0;\r\n}\r\n<\/pre>\n<p>Let&#8217;s look at a more complex solutions where we use length modifiers for our variables. We&#8217;ve also added a column for wages to show floating point numbers.<\/p>\n<ul>\n<li>First of all we should fix how much space is there for each field &#8211; e.g.\u00a0%13s, %3d, %6d. This number in between will say how many spaces to designate for each field. If the value is shorter, it will print whitespace instead. If it is longer however, it will still misalign everything else.<\/li>\n<li>Secondly we use left alignment for text: %-13s.\u00a0 The minus symbol is the key here to left align text. Without any modifier the text would be aligned to the right. Usually we want to align text to the left and numbers to the right.<\/li>\n<li>The third new format we&#8217;re using is %06d. This indicates, that the number will be given 6 characters of space, just as before, however instead of whitespace we will print zeros.<\/li>\n<li>For the last one, we&#8217;ll look at floating point formatting (%5.2f). This means that we will always print two digits after the comma, even if they were zeros. The number before indicates how many places everything will get together, including the floating point separator. 5 in this case would mean that we get 2 numbers before and two number after the comma and one is reserved for the separator (point).<\/li>\n<\/ul>\n<p><a href=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3952\" src=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab3.png\" alt=\"\" width=\"409\" height=\"52\" srcset=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab3.png 409w, https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab3-300x38.png 300w\" sizes=\"auto, (max-width: 409px) 100vw, 409px\" \/><\/a><\/p>\n<h3><span class=\"ez-toc-section\" id=\"Useful_tricks\"><\/span>Useful tricks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Using the tricks we&#8217;ve learned so far, we can also create headers for our tables. In C programs, it doesn&#8217;t matter if we put actual variables or just constants in printf statement after the format. We&#8217;ll use this property to align the text in the header with the rest of the table.<\/p>\n<pre class=\"lang:c decode:true\">#include &lt;stdio.h&gt;\r\n\r\nint main(void)\r\n{\r\n    char *names[] = {\"Ott\", \"Dolores\", \"Johanna-Maria\"};\r\n    int employeeNum[] = {7, 19, 2123};\r\n    int ages[] = {22, 19, 53};\r\n    float wages[] = {13f, 8.95f, 10.1f};\r\n\r\n    printf(\"%-13s  %3s  %6s  %5s\\n\", \"name\", \"age\", \"id #\", \"wage\");\r\n    for (int i = 0; i &lt; 3; i++)\r\n    {\r\n        printf(\"%-13s  %3d  %06d  %5.2f\\n\", names[i], ages[i], employeeNum[i], wages[i]);\r\n    }\r\n    return 0;\r\n}\r\n<\/pre>\n<p><a href=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab4.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3954\" src=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab4.png\" alt=\"\" width=\"414\" height=\"68\" srcset=\"https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab4.png 414w, https:\/\/blue.pri.ee\/ttu\/wp-content\/uploads\/2018\/09\/tab4-300x49.png 300w\" sizes=\"auto, (max-width: 414px) 100vw, 414px\" \/><\/a><\/p>\n<p>The solution is becoming quite impressive already, however there are still a few issues. One of which is changing the length of the field. Currently we need to do it in two places, however it would be preferred to do it in only one place, when needed. Let&#8217;s take a look at achieving this.<\/p>\n<pre class=\"lang:c decode:true \">#include &lt;stdio.h&gt;\r\n\r\n#define F_LEN_NAME 13\r\n#define F_LEN_AGE 3\r\n#define F_LEN_ID 6\r\n#define F_LEN_WAGE 5\r\n\r\nint main(void)\r\n{\r\n    char *names[] = {\"Ott\", \"Dolores\", \"Johanna-Maria\"};\r\n    int employeeNum[] = {7, 19, 2123};\r\n    int ages[] = {22, 19, 53};\r\n    float wages[] = {13f, 8.95f, 10.1f};\r\n\r\n    printf(\"%-*s  %*s  %*s  %*s\\n\", F_LEN_NAME, \"name\",\r\n                                    F_LEN_AGE, \"age\",\r\n                                    F_LEN_ID, \"id #\",\r\n                                    F_LEN_WAGE, \"wage\");\r\n    for (int i = 0; i &lt; 3; i++)\r\n    {\r\n        printf(\"%-*s  %*d  %0*d  %*.2f\\n\", F_LEN_NAME, names[i],\r\n                                           F_LEN_AGE, ages[i],\r\n                                           F_LEN_ID, employeeNum[i],\r\n                                           F_LEN_WAGE, wages[i]);\r\n    }\r\n    return 0;\r\n}\r\n<\/pre>\n<p>The length of the field can be given using a variable or a constant instead of just writing it into the format. To do this, we will write an asterksk (*) instead of the actual number. In this case, the length of the field will be taken from the arguments of that printf statement. First value in this case needs to be the length, given as #define constants, and the second value is from the actual variable. Now all we need to do is change the constant and it will be easy to modify the table column widths.<\/p>\n<p>The next step in this would be making these columns either dynamically changing in widths or just cutting off the excess if a value is too long. To achieve the first, we would need to replace the constants with variables and we would need to scan the entire column for the longest value. The second option would force us to print characters, one at a time, until we run out of room.\u00a0 Which is better out of all the given ideas and solutions depends on the task at hand.<\/p>\n<p>I&#8217;d also like to point out, that due to the line length limit, we&#8217;re splitting this line to make it pleasing to the eye and of course easier to fix if we miss something. Information about this can be found in the coding style.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The following page will list various tips and tricks on using the printf() function. I recommend copying those examples and trying them out for yourself. I also encourage You to try modify some lines or values and see what happens. Every code example has some accompanying text, explaining what the good and bad sides of &hellip; <a href=\"https:\/\/blue.pri.ee\/ttu\/coding-guides\/some-printf-tips\/\" class=\"more-link\">Loe edasi <span class=\"screen-reader-text\">Using printf with tips and tricks<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":4802,"menu_order":2,"comment_status":"closed","ping_status":"closed","template":"page-templates\/code-width-wide.php","meta":{"footnotes":""},"class_list":["post-3992","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/3992","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/comments?post=3992"}],"version-history":[{"count":2,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/3992\/revisions"}],"predecessor-version":[{"id":10257,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/3992\/revisions\/10257"}],"up":[{"embeddable":true,"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/pages\/4802"}],"wp:attachment":[{"href":"https:\/\/blue.pri.ee\/ttu\/wp-json\/wp\/v2\/media?parent=3992"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}