C

C Input Output Function (I/O Function)

C programming language provides many built-in functions to read given input and write data on screen, printer or in any file.

scanf() and printf() functions

scanf() returns the number of characters read by it.
printf() function returns the number of characters printed by it.

//Write a C Program to Get Numeric Input from User
#include<stdio.h>
#include<conio.h>
void main()
{
    int i;
    printf("Enter a value: ");
    scanf("%d",&i);
    printf( "\nYou entered: %d",i);
    getch();
}

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.
For Example if you Enter 5 scanf() will get the value you have entered. and store it to variable i
printf() function prints the value of variable i on screen.

Output:

Command Prompt
Enter a value: 5
You entered 5

getchar() & putchar() functions

The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one characters.
The putchar() function prints the character passed to it on the screen and returns the same character. This function puts only single character at a time. In case you want to display more than one characters, use putchar() method in the loop.

//Write a C Program to Get a Character as Input from User
#include<stdio.h>
#include<conio.h>
void main()
{
    int c;
    printf("Enter a character: ");
    c=getchar();
    putchar(c);
    getch();
}

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.

Output:

Command Prompt
Enter a character: A
A

gets() & puts() functions

The gets() function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (end of file).
The puts() function writes the string s and a trailing newline to stdout.

//Write a C Program to Get String as Input from User
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    printf("Enter a String: ");
    gets(str);
    puts(str);
    getch();
}

When you will compile the above code, it will ask you to enter a string. When you will enter the string, it will display the value you have entered.

Output:

Command Prompt
Enter a String: Tutorialink
Tutorialink

Difference between scanf() and gets()

The main difference between these two functions is described below.

scanf() getch()
scanf() stops reading characters when it encounters a space gets() reads space as character too.
If you enter name as Tutorial ink using scanf() it will only read and store Tutorial and will leave the part after space. gets() function will read it complete Tutorial ink



Subscribe us on Youtube

Share This Page on


Ask Question