Scanf  stands for "scan formatted"

Usage

The scanf function, which is found in C, reads input for numbers and other datatypes from standard input (often a command line interface or similar kind of a text user interface).

The following shows code in C that reads a variable number of unformatted decimal integers from the console and prints out each of them on a separate line:

#include <stdio.h>

int main(void)
{
    int  n;

    while (scanf("%d", &n) == 1)
        printf("%d\n", n);
    return 0;
}

After being processed by the program above, an irregularly spaced list of integers such as

456 123 789     456 12
456 1
      2378

will appear consistently spaced as:

456
123
789
456
12
456
1
2378

To print out a word:

#include <stdio.h>

int main(void)
{
    char  word[20];

    if (scanf("%19s", word) == 1)
        puts(word);
    return 0;
}

No matter what the datatype the programmer wants the program to read, the arguments (such as &n above) must be pointerspointing to memory. Otherwise, the function will not perform correctly because it will be attempting to overwrite the wrong sections of memory, rather than pointing to the memory location of the variable you are attempting to get input for.

In the last example an address-of operator (&) is not used for the argument: as word is the name of an array of char, as such it is (in all contexts in which it evaluates to an address) equivalent to a pointer to the first element of the array. While the expression &wordwould numerically evaluate to the same value, semantically it has an entirely different meaning in that it stands for the address of the whole array rather than an element of it. This fact needs to be kept in mind when assigning scanf output to strings.

As scanf is designated to read only from standard input, many programming languages with interfaces, such as PHP, have derivatives such as sscanf and fscanf but not scanf itself.


 

See Scanf format string

You have no rights to post comments