scanf() prototype
int scanf( const char* format, ... );
The
scanf() function reads the data from
stdin and stores the values into the respective variables.
It is defined in <cstdio> header file.
scanf() Parameters, scanf() does not assign the result to any receiving argument.
- An optional positive integer number that specifies maximum field width. It specifies the maximum number of characters that scan.
scanf() Return value
- If successful, the
scanf()function returns the number of receiving arguments successfully assigned.
- If a matching failure occurs before the first receiving argument was assigned, returns zero.
- If input failure occurs before the first receiving argument was assigned, EOF is returned.
Example: How scanf() function works
#include <cstdio> int main () { FILE *fp; char name[50]; int age; fp = fopen("example.txt","w"); fprintf(fp, "%s %d", "Tim", 31); fclose(fp); fp = fopen("example.txt","r"); scanf(fp, "%s %d", name, &age); fclose(fp); printf("Hello %s, You are %d years old\n", name, age); return 0; }
When you run the program, a possible output will be:
Hello Tim, You are 31 years old