Explain unformatted input and output functions in C language

CServer Side ProgrammingProgramming

Unformatted input and output functions read a single input sent by the user and permits to display the value as the output at the console.

Unformatted input functions

The unformatted input functions in C programming language are explained below −

getchar()

It reads a character from the keyboard.

The syntax of getchar() function is as follows −

Variablename=getchar();

For example,

Char a;
a = getchar();

Example Program

Following is the C program for getchar() function −

 Live Demo

#include<stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("file.txt","w"); //open the file in write mode
   printf("enter the text then press cntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen("file.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF){
      if(fp){
         char word[100];
         while(fscanf(fp,"%s",word)!=EOF) // read words from file{
            printf("%s\n", word); // print each word on separate lines.
         }
         fclose(fp); // close file.
      }else{
         printf("file doesnot exist");
         // then tells the user that the file does not exist.
      }
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter the text then press cntrl Z:
This is an example program on getchar()
^Z
text on the file:
This
is
an
example
program
on
getchar()

gets()

It reads a string from the keyboard

The syntax for gets() function is as follows −

gets(variablename);

Example

 Live Demo

#include<stdio.h>
#include<string.h>
main(){
   char str[10];
   printf("Enter your name: \n");
   gets(str);
   printf("Hello %s welcome to Tutorialspoint", str);
}

Output

Enter your name:
Madhu
Hello Madhu welcome to Tutorialspoint

Unformatted output functions

The unformatted output functions in C programming language are as follows −

putchar()

It displays a character on the monitor.

The syntax for putchar() function is as follows −

Putchar(variablename);

For example,

Putchar(‘a’);

puts()

It displays a string on the monitor.

The syntax for puts() function is as follows −

puts(variablename);

For example,

puts("tutorial");

Sample Program

Following is the C program for putc and getc functions −

 Live Demo

#include <stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w");
   printf("enter the text.press cntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen("std1.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF){
      putchar(ch);
   }
   fclose(fp);
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter the text.press cntrl Z:
This is an example program on putchar()
^Z
text on the file:
This is an example program on putchar()
raja
Published on 26-Mar-2021 07:19:55
Advertisements