Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

The magic and flexibility of printf (part 1)

c printf output

  • Please log in to reply
6 replies to this topic

#1 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 14 October 2012 - 01:30 PM

Hello everyone. I am back after some time with tutorials again and hopefully would continue with momentum.
printf is something every one encounters as soon as they see their first “hello world” program in c
It is a very common and fundamental, as well as a flexible and powerful function.
 
So I thought of assembling together all info i.e. starting from the basics to the less known and advanced territories of this function.

We will try to assume minimum basic knowledge such as you know what data types are i.e. int, char, float, double, string (string is not a data type itself but represented by a null terminated character array) etc. but nothing beyond that.
 
Also, check out our tutorials on scanf and sscanf!

Basics
So printf is mainly used when you want to print anything to screen / console. The infamous hello world program is below for your reference.


printfhelloworld.jpg

The most primitive things are that it is a function whose code is located under header file stdio.h. However, this is often the library that compilers include by default. This is the reason that you often are able to use it even without including stdio.h.

The first aspect is “whatever you pass to printf() in double quotes is printed as it is on screen” with some exceptions of course such as ‘\n’ which simply tells us to print a new line. The character ‘\’ is called an escape sequence and is NOT treated as any normal character to print. We will get back to it in more detail shortly.

A few quick examples:

printf(“how \t are you? \n A backslash \\”);

\t prints a tab (4 spaces generally), \\ prints a single normal back slash because the second \ tells that it is nothing but an actual slash itself.

char *s = “string constant\n”;
printf(s); // prints ‘string constant’ because s points to the same string

Now as a format string, one can embedded any type of variables in a printf string i.e. characters, integers, floats, doubles, or other strings themselves. The key to do this is ‘%’ character. Anywhere % is seen in a printf string, it means this is no ordinary character, but it is followed by a variable of some data type. The data type is indicated by c for char, d for signed integer, s for string etc. Note that this is still present inside the double quotes i.e. “” (e.g. %d, %c, %s). However, logically speaking we also need to specify which variable to print whose value will be replacing the %<type>. So the double quotes are followed by a comma, and then contain the name of variable. If there are more, then each of these names is separate by commas. Note that there should be as many variables after the double quotes as there are %<type> in the quotes themselves. If this is not the case, you may not get an error but the result is undefined. Let’s see more examples

char a = ‘k’
printf(“Hi character %c\n”, a); // prints Hi character k

int integer = 10;
printf(“%d\n”, integer); // prints 10 followed by a newline. A string can only contain a %<type> too

double db = 12.003;
printf(“%f\n”, db); // prints 12.003000 – Double and float variables both use %f and by default print six places after the decimal.

However, if you like to specify how many places to print after the decimal, you can do that as follows

printf(“%[b].2[/b]f\n”, db); // prints 12.00

Inserting a .<number of digits you want to print> between % and f will do the job. Note that this does a rounding off too i.e. if number was 12.005 (or greater) it would print 12.01 but 12.00 if less as in above example.

long lg=100;
unsigned int un = 20;
printf(“%l\n”, lg); // prints 100
printf(“%u\n”, un) // prints 20

These prefixes can be combined where it makes sense such as

unsigned long var = 100000;
printf(“%lu\n”, var); // prints 100000 which is an unsigned long variable

In case of strings

char s[] = “I am string”;
char *t = “another type of string”;
printf(“%s %s\n”, str, t);

The above prints both strings (first followed by the second) on a single line.

Similarly, hexadecimal integer

int a = 10; // 0xA in hex
printf(“%x %X\n”, a, a); // prints a and A – Note that small %x prints small case hex and vice versa.

To print a single % on screen, just use two %% together.

Also, %e is used for scientific notation of a float or double. Moreover using %g would mean use either of %f or %e which ever appears shorter in printing. %o is used for octal.

You can also specify the width of particular field

printf(“M\n”, a); // prints 10 but with two spaces in the beginning to complete field width of 4.

If ‘a’ contains a 3 digit value then there would only be a single space in the beginning. However, this does not truncate values. So if a=10000, it would still print the 5 digit value. This can be helpful when you are printing a table of values and you set a maximum width so all numeric values are pretty printed right aligned.

This also applies to strings.

printf(“0s\n”, s); // prints the string s in a field 30 characters wide right aligned.

If for some reason you need to override the right justification (which is default) you can precede with a ‘-’ sign

printf(“%-30s\n”, s); // prints the string s in a field 30 characters wide but left aligned padded by spaces.

That is so far with the basics and most common uses.

 

Click here for Part 2 of this tutorial.


Edited by Roger, 19 February 2013 - 02:37 PM.
linking

  • 1
Today is the first day of the rest of my life

#2 Chall

Chall

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 349 posts
  • Location:Cedar Rapids, IA
  • Programming Language:Java
  • Learning:C, Java, C++, C#, Python, JavaScript, Assembly

Posted 15 October 2012 - 03:21 PM

Very good. Helped me to understand a little bit more about the functionality of the printf function. :)
  • 0
Speaks fluent Java

#3 VNFox

VNFox

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 648 posts
  • Programming Language:C#, PHP
  • Learning:Assembly

Posted 15 October 2012 - 03:45 PM

Very nice ... thanks
  • 0

www.pickmike.com
I don't just develop software. I find solutions to your business needs.


#4 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 15 October 2012 - 07:44 PM

I am glad to hear it was helpful. Please feel free to ask any questions or problems you face in using. I will soon follow up with more ones of this sort.
  • 0
Today is the first day of the rest of my life

#5 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 01 November 2012 - 11:40 AM

I have posted follow up of above http://forum.codecal...-2/#entry643238
  • 0
Today is the first day of the rest of my life

#6 object

object

    CC Regular

  • Member
  • PipPipPip
  • 35 posts
  • Programming Language:C, C#, JavaScript

Posted 05 January 2013 - 04:07 PM

We will try to assume minimum basic knowledge such as you know what data types are i.e. int, char, float, double, string etc. but nothing beyond that.


string is not a data type, but a data representation. eg. a string is a sequence of bytes that ends at the first '\0' character.

char *s = “string constant\n”;
printf(s); // prints ‘string constant’ because s contains the same string

No. s contains a pointer value that points at the string formed by "string constant\n". The pointer value isn't required to be a string, though it is required to be a pointer to a string.

The first aspect is “whatever you pass to printf() in double quotes is printed as it is on screen” with some exceptions of course such as ‘\n’ which simply tells us to print a new line.

It sounds like you're confusing string literals with the printf format argument. Neither printf nor the printf format argument will handle any escape sequence translation. Perhaps it'd be wisest to do a separate tutorial on string literals.

In all of these "basics", I see no mention of how to access printf! I would presume this to be a basic fundamental of printf, correct? Which header should I include to access printf? Put this in your tutorial, please.

Edited by object, 05 January 2013 - 04:13 PM.

  • 0

#7 fkl

fkl

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 417 posts

Posted 06 January 2013 - 09:50 PM

string is not a data type, but a data representation. eg. a string is a sequence of bytes that ends at the first '\0' character.


String certainly isn't a type in c, nor did i intend saying so. Intent was that a person understands and is able to use null terminated array representation. However, for a new user, i agree the wording could mislead. Have added the correction. Thanks.

No. s contains a pointer value that points at the string formed by "string constant\n". The pointer value isn't required to be a string, though it is required to be a pointer to a string.


This is taken without the context. The comment was simply referring to s being able to access the string. The assumption that i am trying to say "s contains the string" is totally wrong and i don't think it appears that way if read through the context. Still i have edited the comment to "s points to". I don't want to go here into unnecessary detail of s being a pointer variable which contains a hexadecimal address of a location where the string literal is present. This is over complicating things for a beginner in my opinion and i say this from over ten of experience programming in c. The first time i learned it, it was sufficient to know "s is pointer pointing to the string" which i have edited in comments.

It sounds like you're confusing string literals with the printf format argument. Neither printf nor the printf format argument will handle any escape sequence translation. Perhaps it'd be wisest to do a separate tutorial on string literals.


May be it's something i missed but fail to see the relation drawing the above conclusion from the commented line. It simply said printf prints any string constants passed to it vs escape sequences which have specific meaning in the output. The focus is use here, not the internals of how they are represented or handled. That being said, there is a series of string tutorials too.
http://forum.codecal...stringh-part-1/

In all of these "basics", I see no mention of how to access printf! I would presume this to be a basic fundamental of printf, correct? Which header should I include to access printf? Put this in your tutorial, please.


The header file is clearly visible in the first image in the post as well as mentioned in the first line after that. Please read through well before suggesting some thing not being mentioned.

Edited by fkl, 06 January 2013 - 10:07 PM.

  • 1
Today is the first day of the rest of my life





Also tagged with one or more of these keywords: c, printf, output

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download