Thursday, 28 October 2010

scanf()


It is used to read the values from the keyboard
It is defined in <stdio.h>
It is a input function.
The library stdio.h includes the function scanf(), which takes a text stream from standard input (the keyboard), extracts the data according to format instructions and stores the data in variables.
Like the function printf(), we can describe use a format control string to describe the input data.
Ex: I want to read 234.2

I want to read one character and decimal number( float) from the keyboard.
 ‘B’,18.23
float price;
char code;
scanf(“%c %f”,&code,&price);


I/O of integers in C



#include<stdio.h>
int main()
{
    int c=5;
    printf("Number=%d",c);
    return 0;
}
Output
Number=5
Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this conversion format string matches with remaining argument,i.e, c in this case, value of c is displayed.

#include<stdio.h>
int main()
{
    int c;
    printf("Enter a number\n");
    scanf("%d",&c);
    printf("Number=%d",c);
    return 0;
}
Output
Enter a number
4
Number=4
The scanf() function is used to take input from user. In this program, the user is asked a input and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c and value is stored in that address.


What is wrong in this statement?  scanf(%d,number);


An ampersand & symbol must be placed before the variable name number.
Placing & means whatever integer value is entered by the user is stored at the address of the variable name. This is a common mistake for programmers, often leading to logical errors. 

You may like the following posts:
scanf("%[^\n]
printf()
Input output statements in c

No comments:

Post a Comment