scanf

The command scanf can be used in C programs to input data. scanf has similar syntax to printf. The general form is shown below.

	scanf ( <format string>, arg1, arg2, arg3, ... ) ;

With scanf, the format string specifies the type of data the program is expecting to get from the user. The list of arguments are the variables where the data should be stored. printf and scanf use the same control characters for the various variable types.

scanf will store the data it receives in the memory location where the variable is stored. In order to do this, it needs the memory location of the variable. Preceding the variable name with an & indicates the address of the variable, rather than the variable itself. For instance, the following command will read an integer and store it in the variable index.

    int index;
    scanf("%d", &index);

The sample code below shows various examples of scanf usage.

#include <stdio.h>

int main(int argc, char* argv[])
{
    int sample;
    float fl;
    char string[33]; /*string that will hold 32 characters plus the termination character*/

    printf("Type an integer: \n");
    scanf("%d", &sample);

    printf("Type a string: \n");
    scanf("%s", string);

    printf("Type a float: \n");
    scanf("%f", &fl);


    printf("You typed the integer %d, the string %s, the float %f\n", sample, string, fl);

    /*you can also capture multiple values with one scanf*/
    /*scanf returns the number of values it receives, so a 
	  program can check to make sure all the desired data was
	  received*/

    int dataReceived = 0;
    int testInt;
    float testFloat;

    printf("Enter an int and a float separated by a space\n");

    dataReceived = scanf("%d %f", &testInt, &testFloat);

    printf ("Scanf received %d items of data.  You entered the int %d and the float %f .\n", dataReceived, testInt, testFloat);

    return 0; 
}

A sample run of the program shows the data that the user entered and the results of the program run.

Type an integer:
45
Type a string:
happy23
Type a float:
6.879
You typed the integer 45, the string happy23, the float 6.879000
Enter an int and a float separated by a space
51 1.235
Scanf received 2 items of data.  You entered the int 51 and the float 1.235000 .

next


 home                      table of contents                      about