Download C tutorial – printf, format specifiers, format conversions and formatted output codingunit programming tutorials and more Study Guides, Projects, Research Information Technology in PDF only on Docsity!
Home About Search rss posts
C Tutorial – printf, Format Specifiers, Format
Conversions and Formatted Output
In this C programming language tutorial we take another look at the printf function. We will look at how to use format specifiers to print formatted output onto the screen. The topics covered are; a little printf background, format specifiers and conversions, formatting of different types and format conversions of strings.
printf Background
The printf function is not part of the C language, because there is no input or output defined in C language itself. The printf function is just a useful function from the standard library of functions that are accessible by C programs. The behavior of printf is defined in the ANSI standard. If the compiler that you’re using conforms to this standard then all the features and properties should be available to you.
Format Specifiers
There are many format specifiers defined in C. Take a look at the following list:
%i or %d int %c char %f
float (see also the note below) %s string
Note: %f stands for float, but C language has also a thing called “default argument promotions”. Default argument promotions happen in variadic functions. Variadic functions are functions (e.g. printf) which take a variable number of arguments. When a variadic function is called, after lvalue to rvalue, array to pointer, and function to pointer conversions, each argument that is a part of the variable argument list undergoes additional conversions known as default argument promotions: float arguments are converted to double as in floating point promotion bool, char, short, and unscoped enumerations are converted to int or wider integer types as in integer promotion So for example, float parameters are converted to doubles, and char’s are converted to int’s. If you
actually needed to pass, for example, a char instead of an int, the function would have to convert it back. That’s enough on that side step of variadic function and “default argument promotions”. Let us take a look at an example of printf formatted output (that why you here, isn’t it?):
#include<stdio.h> main(){ int a,b;float c,d; a = 15;b = a / 2; printf("%d\n",b);printf("%3d\n",b); printf("%03d\n",b); c = 15.3;d = c / 3; } printf("%3.2f\n",d);
Output of the source above:
(^77) (^007) 5.
As you can see in the first printf statement we print a decimal. In the second printf statement we print the same decimal, but we use a width (%3d) to say that we want three digits (positions) reserved for the output. The result is that two “space characters” are placed before printing the character. In the third printf statement we say almost the same as the previous one. Print the output with a width of three digits, but fill the space with 0. In the fourth printf statement we want to print a float. In this printf statement we want to print three position before the decimal point (called width) and two positions behind the decimal point (called precision). The \n used in the printf statements is called an escape sequence. In this case it represents a newline character. After printing something to the screen you usually want to print something on the next line. If there is no \n then a next printf command will print the string on the same line. Commonly used escape sequences are: \n (newline) \t (tab) \v (vertical tab) \f (new page) \b (backspace)
main(){ printf("The color: %s\n", "blue");printf("First number: %d\n", 12345); printf("Second number: %04d\n", 25);printf("Third number: %i\n", 1234); printf("Float number: %3.2f\n", 3.14159);printf("Hexadecimal: %x\n", 255); printf("Octal: %o\n", 255);printf("Unsigned value: %u\n", 150);
} printf("Just print the percentage sign %%\n", 10);
Output of the source example:
The color: blueFirst number: 12345 Second number: 0025Third number: 1234 Float number: 3.14Hexadecimal: ff Octal: 377Unsigned value: 150 Just print the percentage sign %
Note: In the last printf statement only the percentage sign is printed. The number 10 in this statement doesn’t matter; it’s not used in the output. So if you want to print a percentage number you would use something like this: printf(“%2d%%\n”, 10); (The output will be 10%)
Formatting Strings
By now you have seen most of the format conversion possible, but there is one type that is a little different and that are string format conversions. Take a look at the following example:
#include<stdio.h> main(){ printf(":%s:\n", "Hello, world!");printf(":%15s:\n", "Hello, world!"); printf(":%.10s:\n", "Hello, world!");printf(":%‐10s:\n", "Hello, world!"); printf(":%‐15s:\n", "Hello, world!");printf(":%.15s:\n", "Hello, world!"); printf(":%15.10s:\n", "Hello, world!");printf(":%‐15.10s:\n", "Hello, world!"); }
The output of the example above:
:Hello, world!:: Hello, world!: :Hello, wor::Hello, world!: :Hello, world!:Hello, world!: : ::Hello, wor Hello, wor: :
As you can see, the string format conversion reacts very different from number format conversions. The printf(“:%s:\n”, “Hello, world!”); statement prints the string (nothing special happens.) The printf(“:%15s:\n”, “Hello, world!”); statement prints the string, but print 15 characters. If the string is smaller the “empty” positions will be filled with “whitespace.” The printf(“:%.10s:\n”, “Hello, world!”); statement prints the string, but print only 10 characters of the string. The printf(“:% 10s:\n”, “Hello, world!”); statement prints the string, but prints at least 10 characters. If the string is smaller “whitespace” is added at the end. (See next example.) The printf(“:% 15s:\n”, “Hello, world!”); statement prints the string, but prints at least 15 characters. The string in this case is shorter than the defined 15 character, thus “whitespace” is added at the end (defined by the minus sign.) The printf(“:%.15s:\n”, “Hello, world!”); statement prints the string, but print only 15 characters of the string. In this case the string is shorter than 15, thus the whole string is printed. The printf(“:%15.10s:\n”, “Hello, world!”); statement prints the string, but print 15 characters. If the string is smaller the “empty” positions will be filled with “whitespace.” But it will only print a maximum of 10 characters, thus only part of new string (old string plus the whitespace positions) is printed. The printf(“:% 15.10s:\n”, “Hello, world!”); statement prints the string, but it does the exact same thing as the previous statement, accept the “whitespace” is added at the end. A little warning! The printf function uses its first argument to determine how many arguments will follow and of what types they are. If you don’t use enough arguments or if they are of the wrong type than printf will get confuses, with as a result wrong answers. That’s all for this C tutorial. Just make some examples of your own, they are easy to make. This is the only way to learn and see how the format conversions reacts. This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! or use ShareThis to share this post with others.
There are currently 145 responses to “C Tutorial – printf, Format Specifiers,
Format Conversions and Formatted Output”
Why not let us know what you think by adding your own comment!
- Joe on November 11th, 2009: this tutorial is very good!!!!!
1.23457e+ 9.87653e+ 4.56793e+ What I need is this: 12345678
Could anyone help me?
- Social Media Graphics on February 12th, 2010: @Armando – just change printf (“%g\n”, arr[i]); to printf (“%f\n”, arr[i]);
- Armando on February 17th, 2010: @Social Media Graphics thanks for your suggestion. But what I really need is to print the decimal significant if any, otherwise only the integer part.
- cheeloon on March 4th, 2010: Very good and detail explanation. Thx alot.
- Joe on March 12th, 2010: if i have 1294300000000000.000001, how do i get 0.000001? i only want the decimal places…. does anybody know?
- prashanth on April 7th, 2010: your tutorial was very helpful to me……..thank a lot……
- David on April 8th, 2010: Joe: to get the decimal part of a float (or double), try this: float x=1294300000000000.000001; float decimal = x – (int)x; the conversion to an int should truncate the decimal off. However, I should warn that decimal might not be exactly .000001 here because that is actually impossible to represent in binary, because it is in fact in binary a repeating “decimal.” You might also get nicer results using larger data types like doubles and longs.
- Shashika on July 7th, 2010: Thanks For Your Very Helpful Tutorial
- selva on July 8th, 2010: thank u ….. superb explanation …. it made me clear in formatting strings…..
- pramit on July 17th, 2010: answer to armando problem on 12 th feb. just write printf(“%.8g\n”,arr[i]); printf(“%.11g\n”,arr[i]); printf(“%.10g\n”,arr[i]); note:u have to write like above,but not in loop bcoz this only serve ur requirement. waiting for ur another problem.
- Tushar Srivastava on July 31st, 2010: Good stuff for beginners but you should include some examples of %U format specifier with its explanation. Best of Luck
- Holo on August 19th, 2010: Very good exmples – I am using this in awk but How do I print 10,123,456 – comma after each thousand. I saw some where else to use “%’d” but that is causing problem. ANy ideas. Thanks
- Matt Bates on August 24th, 2010: i am trying to print two strings that are stored in char arrays. I can’t get them onto the same line. char firstName[50]; char lastName[50]; printf(“Your name is %s”, firstName, lastName); it prints out: Your name is ‘firstName’ ‘lastName’ how do i get them onto the same line??? In other words, how to I add to the printf function?
- admin on August 25th, 2010: @ Matt Bates – The source code you have given should only print ‘firstName’, because you only use one %s in your printf statement. So I don’t know why it’s also printing ‘lastName’ (maybe an extra printf statement that you’ve not put in your example.) But below you’ll find an example that should do what you want:
You could also use the “itoa” function (from stdlib.h) with a radix of 2 to do the conversion from an integer to a string that represents the binary value of the integer.
- Deon Joubert on January 19th, 2011: @tallen My previous comment is for you
- aaron on January 24th, 2011: Hello, I need to print 10 numbers with one number per line and then beside each number display the running total of digits in the numbers. example: num digits 3 1 78 3 890 6 1000 10 etc.. I know a couple of methods to do this and they work. But I am asked to use the “%n conversion specifier” or the ‘n’ format specifier(not even sure what it is actually known as). I guess this would be within the printf as I print out the numbers. But I have tried to search around to find out how this conversion specifier works but have figured out barely anything. I am lost as to how this method would work in counting and displaying the running total of digits. If somebody could point me in the right direction I would greatly appreciate it. Thank you.
- nancy on March 1st, 2011: vry useful tutorial
- sha on March 25th, 2011: Great Tutorial. very informative…..
- Faisal on April 13th, 2011: Really helpful and informative tutorial. I hope every one likes it.
- Orel on May 6th, 2011: Best c printf tutorial so far.. great job!
- aayush on May 9th, 2011: awesome man!!!!!!!! nice tut..
- Pisio on May 11th, 2011: Hi all, I need to print a floating number (for example 1009.23) without the decimal point (in this case 100923), just to put it in a formatted positional output. Can I use printf in some way to do this? Thank you!
- ranjitha g on May 20th, 2011: awesome…this tut helped me lot.
- Rahul Singh Chouhan on May 27th, 2011: i need to know how to print bits or bytes character value in c
- praga on June 7th, 2011: hi dude s this is praga ….i need to know exactly whats the reason that we enclose the words to be displayed….meant the words in printf to be enclosed in double quotes
- praga on June 7th, 2011: this tut is gr
- Printf() function for debugging process on June 13th, 2011: […] Have you checked out Keil's User Guide: Cx51 User's Guide – printf() A couple of good tutorials: C Tutorial – printf, Format Specifiers, Format Conversions and Formatted Output Secrets of “printf” The Keil compiler sends printf() output to STDOUT, which I […]
- Anchal on June 16th, 2011: nice explanation given!!!!!
- sahtihi on June 29th, 2011: Very clear and detailed explanation is given
- Ganesh Auti,Pune on July 4th, 2011: very nice tut…
- Aravind on July 5th, 2011: Simple stuff but helps a lot in real life programming. Thanks for the information.
- Brindha on July 15th, 2011: Excellent explanations…. It helps a lot.. Thank u…
- Csaba on November 8th, 2011: Just what I needed, with great examples! Thank you!
- Usman Akram Punjab University Lahore on November 19th, 2011: This website helps me a lot. thanx
- sunny on November 19th, 2011: this is wat i want thanks…
- Neeba on November 24th, 2011: good one.
- Prash on December 31st, 2011: anybody suggest me plz ?? is there any difference between ++a and a++ and when we assign a=2 then what what will return by above ++a and a++ !!!!!
- Prash on December 31st, 2011: anybody suggest output ???? int main() { int i=2; for(;i<4;) printf("%d %d ", i++,++i) return 0; }
- Naveed on January 3rd, 2012: very nice……. thanks.
- Anurag Dake on January 12th, 2012: #include int main() { float f=43.20; printf(“%e\n”,f); printf(“%f\n”,f);
printf(“%g\n”,f); return 0; } What are the significance of %e,%g in the above program?
- Anurag Dake on January 12th, 2012: @Prash The o/p will vary compiler to compiler
- Rahul on January 19th, 2012: { char c[]=”GATE2011″; char *p=c; printf(“%s”,p+p[3] p[1]); } o/p is 2011 please explain how the o/p is coming 2011?
- vidya on January 29th, 2012: thanx for the tutorial…helped me a lot in understanding string format conversions with all the width and precisions
- Ragavi on January 31st, 2012: How to print values of variables without using format specifier pl help me
- Dario on February 9th, 2012: Very very useful information. Very complete and simple. The best “printf” tutorial so far. Is there some similar tutorial about “scanf”?
- smith on February 17th, 2012: float B=9876.54321; printf(“\n\t%12.5G”,B); why the out put is not 9876.54321?
- Cad on February 17th, 2012: @smith : This is because of the specifier G. The specifier G outputs the shorter of %E or %f. But the precision value is interpreted differently in “G” format than in “f” format. The precision for “f” specifies the number of digits after the decimal point. The precision for “G” specifies the maximum number of significant digits printed. Try the three specifiers by printing the value, for example: #include<stdio.h>
- Vipin Patel on June 5th, 2012: thanks a lot,
- Jackouille on June 10th, 2012: Very nice but I have a complicated display to put: I got the two first digits of an IP address (in float) and I would like to display it but with always the. (dot) in 4th position and the correct value for the second octet. Currently it gives me: 25.000 instead of 25. 138.350 instead of 138.35 and dot are not aligned. Do you have a magic way to proceed only with format specifier because I can only provide a format, not add new values?
- ayush on June 26th, 2012: very helpful in understandind concept of format specifier
- Bhavanishankar on July 5th, 2012: Its very usefull to all & it is very good…nice tutorial..
- shalini on July 5th, 2012: Q)) char c=”gate2011″; char*p=c; printf(“%s”,p+p[3] p[1]); what wil be the output of the following code fragment??
- admin on July 6th, 2012: @shalini – First of it should be char c[] = “gate2011″; otherwise you’ll get something like – warning: initialization makes integer from pointer without a cast. But if you run the code the output will be 2011.
- sarir on July 13th, 2012: char *c=”gate2011″ ….. … will give output 2011 becoz Going through each line in turn: char c[] = “gate2011″; Let’s assume that array c is located at memory address 200. char *p = c; p is now a pointer to c. It therefore points to memory address 200. The actual content of p is “200”,
indicating the memory address. printf(“%s”, p + p[3] – p[1]); The value of p is 200 when we treat it like a pointer. However, we can also treat it like an array. p[3] gets the value of the 4th item in the string, which is “e”. C stores characters as their ASCII value. The ASCII value of “e” is 101. Next, we get the value of p[1]. p[1] == “a”, which has an ASCII value of 97. Substituting these into the function: printf(“%s”, 200 + 101 – 97); That evaluates to: printf(“%s”, 204); At memory address 204, we have the string “2011”. Therefore, the program prints “2011”.
- David Blaine Fullerton on July 13th, 2012: Why don’t you put some // example 1 // at end where it is easier to see along with matching that when you print it out. Because it takes longer the way it is listed. You have 6 / 7 things, hard to tell which line.
- venu nishad on July 29th, 2012: this tutorial is very useful thanks for help………
- harisha on August 8th, 2012: thank U for this helpfu tutorial.
- sukesh on August 16th, 2012: its really very helpful to me. so, thanks a lot.
- jeff on August 19th, 2012: Thanks this really help me to flashback
- sangeetha on September 2nd, 2012: thank u so much it used to my studies thanks a lot
- Rishi on September 10th, 2012: This website rox !!!!!
- arist on September 16th, 2012: How to printf the \n itself?
- admin on September 16th, 2012:
Thank you for your problem
- jasleen on November 25th, 2012: Very nicely explained
- Suraj Rana on November 27th, 2012: Thanx a lot.This really helped me with my exam preparations.
- janardhan on December 5th, 2012: thank u sir ,it is useful.
- Haris on December 5th, 2012: Thanks a lot. They are very helpful for us.
- jason on January 9th, 2013: very useful, concise and complete!
- Subbu on January 18th, 2013: Crisp & Clear explanation..!! Thanxx
- Printf Formats | Code Thrower on February 10th, 2013: […] In C, printf is a powerful function with many formats. I found a very good tutorial here. […]
- Tutorial Pinguino – Capitulo 7. USB CDC Emulación de Puerto Serie | Blog MicroEmbebidos (PIC,MSP430,LPC,RTOS) on March 31st, 2013: […] este enlace pueden encontrar diversos ejemplos con el printf para conocer como formatear variables y las prueben […]
- Ayesha on April 1st, 2013: relli gud tutorial… thnx a lot..
- neeraj on April 8th, 2013: its gud…
- Sadam Hussain on April 8th, 2013: This is very helpful… I like it very much, I hope this will be benificial for everyone……….
- Steve on April 14th, 2013: I need to print out a float containing a GPS coordinate in decimal values, which is 3.6 (ie: 123.123456) The last digit(6) is critical since I am measuring down to within 3 meters, and require accurate
logging and terminal data parsing. Is there any way to print the value as well as parsing the float into a string while keeping the precision? float f2= 80.123456; sprintf(op, “string %3.6f”, f2); printf(op); returns: string 80. — OR — Is there another way I can parse the value from a string to a decimal and keep the precision? char read[10] = “ 80.123456″; float lon = (1000000 * (float)atoi(read)); printf(“lf %3.6f\n”, lon); returns: lf 80000000. I am willing to split the char value into 3 integers, (high=” 80″, mid=”123″, low=”456″) but not sure how to parse it in to parts while maintaining precision. (value range “123.123456” to “ 101.123456″ read as a string)
- Amy on April 15th, 2013: I need to print something in the format 0.144231E 03 or 0.88913E+03 etc so 0.number with scientific notation. Any ideas? Normal scientific notation (e.g. 5.1498587E+03 or 1.2039404 03 etc is no good, I can’t use if for what I need to do)
- weethomas on May 21st, 2013: @Steve, I hope you realize that unless your GPS is accurate to 3 meters, you are not going to actually have 3 meters of accuracy, regardless of how many decimal points it reports. Regarding your storage issue. Single precision floats have at most 6 to 9 decimal digits of precision. When converting to a string, you are essentially generating a decimal representation of that float. This means that you are guaranteed that a number with 6 decimal digits can be converted back and forth between a float and it’s string representation (which is decimal). However, any more than that really depends on the number (ie some 7, 8, and 9 digit decimals can be converted exactly while others won’t). So, in your case, you have an 8 digit decimal number that you first convert to float, then back to decimal (in string form). You should expect that at most, the first 6 digits will match. In you second example, you used atoi which converts an ascii string to an integer. Integers are whole numbers. They don’t have decimal points. So, the output is exactly what you should have