Lecture12 C Input Output Functions
Lecture12 C Input Output Functions
The %d, %f, %c, %s simply lets the compiler know the type of variable value
being read in.
When the program reaches the scanf() statement it pauses to give the user
time to type something on the keyboard and continues only when the users
press <Enter>, or <Return>, to signal that he, or she, has finished entering
the value.
scanf("%d %d",&i,&j), will read in two integer values into i and j.
© Prof Suvendi Rimer, UJ
Input Function: scanf() Example
#include <stdio.h>
int main(void)
{
int iAge;
float fBal;
char sPet[100];
printf("Enter your age, wallet balance and favourite pet name. \n");
scanf("%d %f %s", &iAge, &fBal, sPet);
printf("Your age is %d, your wallet balance is R%.2f and your favourite pet is
%s\n", iAge, fBal, sPet);
}//main
The program stores the value in iAge, fBal and sPet.
Each time the program is run, the user gets a chance to type in a different value
to the variable and the program also gets the chance to produce a different
result!
Note: the scanf() function does not prompt for an input. You should
get in the habit of always using a printf() function, informing the user
of the program and what they should type, before a scanf()
© Prof Suvendi Rimer, UJ
function.
Output Function: printf()
The printf() (and scanf()) functions can take a variable number of
parameters.
The first parameter of printf() is always a string (e.g. "Hello World") but after
that you can include as many parameters of any type that you want to.
The format for using the printf() function is:
printf(string,variable,variable,variable...);
where the ... means you can carry on writing a list of variables separated by
commas as long as you want to.
The string is usually called the control string or the format string and it
specifies the type of each variable in the list and how you want it printed.
printf() scans the string from left to right and prints on screen any characters
it encounters - except when it reaches a % character.