Sunday, May 5, 2013

Scanf working

The scanf function allows you to accept input from standard in, which for us is generally the keyboard. The scanf function can do a lot of different things, but it is generally unreliable unless used in the simplest ways. It is unreliable because it does not handle human errors very well. But for simple programs it is good enough and easy-to-use.
Scanf syntax:
scanf("%d", &b);
The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is printf, so b must be declared as an int) and place that value into b.
The scanf function uses the same placeholders as printf:
  • int uses %d
  • float uses %f
  • char uses %c
  • character strings use %s
You MUST put & in front of the variable used in scanf because it shows the adress of variable.

In general, it is best to use scanf() as shown here -- to read a single value from the keyboard. Use multiple calls to scanf to read multiple values. In any real program, you will use the gets() or fgets() functions instead to read text a line at a time. Then you will "parse" the line to read its values. The reason that you do that is so you can detect errors in the input and handle them as you see fit.
The printf and scanf functions will take a bit of practice to be completely understood, but once mastered they are extremely useful.

                                    Try this

 

Modify this program so that it accepts three values instead of two and multiply all three together:

#include <stdio.h>
#include<conio.h>
void main()
{
    int a, b, c;
    printf("Enter the first value:");
    scanf("%d", &a);
    printf("Enter the second value:");
    scanf("%d", &b);
    c = a * b;
    printf("%d * %d = %d\n", a, b, c);
    getch();
}
You can also delete the b variable in the first line of the above program and see what the compiler does when you forget to declare a variable. Delete a semicolon and see what happens. Leave out one of the braces. Remove one of the parentheses next to the main function. Make each error by itself and then run the program through the compiler to see what happens.

No comments:

Post a Comment