Computer >> Computer tutorials >  >> Programming >> C programming

scanf() and fscanf() in C


Function scanf()

The function scanf() is used to read formatted input from stdin in C language. It returns the whole number of characters written in it otherwise, returns a negative value.

Here is the syntax of scanf() in C language,

int scanf(const char *characters_set)

Here is an example of scanf() in C language,

Example

#include <stdio.h>
int main () {
   char s[20];
   printf("Enter a string : ");
   scanf("%s", s);
   printf("\nEntered string : %s\n", s);
   return(0);
}

Output

Enter a string : Peter!
Entered string : Peter!

Function fscanf()

The function fscanf() is used to read the formatted input from the given stream in C language. It returns zero, if unsuccessful. Otherwise, it returns The input string, if successful.

Here is the syntax of fscanf() in C language,

int fscanf(FILE *stream_name, const char *set_of_characters)

Here is an example of fscanf() in C language,

Example

#include <stdio.h>
#include <stdlib.h>
int main () {
   char str1[10];
   int year;
   FILE * fp;
   fp = fopen ("file.txt", "w+");
   fputs("This is demo text!", fp);
   rewind(fp);
   fscanf(fp, "%s", str1);
   printf("First word = \n%s\n", str1 );
   fclose(fp);
   return(0);
}

Output

First word =
This