Sep 4, 2016

C Programming #87: stdio - printf, scanf

C Programming #87: stdio - printf, scanf

Following article explores formatted stdio functions printf and scanf. printf and scanf are varidac function (function that take variable arguments). Variable argument function are covered in later articles.


int printf(const char *format, ...);

Here are the simplest use of printf without using any format specifiers.

#include <stdio.h>
int main()
   char *p = "This is pointer to const string\n";
   printf("This is const string\n");
   printf("Hello " "World\n");
   return 0;
This is const string
This is pointer to const string
Hello World

If you want to print the content of the variable we need to use format specifier in format string and variable is passed as argument to printf. Since you can print variable number of variables printf is a varidac function. We will cover how to write a varidac function later in this series of article.

Now different format specifier that is available are as follows. Each format specifier is prepended by %.

Format specifier Details
d, i signed integer
u unsigned integer
o unsigned octal
x, X unsigned hex
f, F Double
e, E Double exponential
g, G either f or e
a, A Hex Double(Added in C99)
c unsigned char
s string(const char *)
p pointer
% character '%'


int scanf(const char *format, ...);

It is used to take input from the user. But one thing we need to make sure is that we need to pass the address of variable here. This is common point of mistake most of the novice programmer makes.

#include <stdio.h>
int main()
   int a;
   scanf("%d", &a);
   printf("value of a is %d", a);
   return 0;
value of a is 0

Same format specifier that were discussed earlier can be used here to. We could do lot of formatting using format specifier which will be covered in next article.

No comments :

Post a Comment