Input/Output (I/O) in C Programming - IndianTechnoEra
Latest update Android YouTube

Input/Output (I/O) in C Programming

Introduction, Format Specifier,Standard I/O Functions,printf(), scanf(),getchar(), putchar(),Return Type, Scansets, File I/O, Error Handling

 

Introduction:

Input/output, or I/O, is a fundamental concept in programming, and it is no exception in the C programming language. 

In fact, C provides a standard I/O library that includes functions for reading and writing data from various sources. 

This library is useful for operations such as reading input from the keyboard or a file, and writing output to the screen or a file. 

These I/O operations are critical for programs that need to interact with the user or store data on a storage medium.


Format Specifier:

In C, a value can be a character type, integer type, float type, and so on. 

To display these values we have format specifiers used in printf function. 

These format specifiers start with the percentage symbol ‘%’. 

Some of the commonly used format specifiers are given below.

  • %d - for printing integers
  • %f - for printing floating-point numbers
  • %c - for printing characters
  • %s - for printing strings
  • %p - for printing memory addresses
  • %x - for printing hexadecimal values

All commonly used format specifiers: 

%dfor integers
%ffor floating-point numbers
%cfor characters
%sfor strings
%pfor memory addresses
%ifor unsigned integers
%x or %Xfor hexadecimal values
%e or %Efor scientific notation of floats
%g or %Gfor floats with current precision
%ld or %lifor long integers
%lffor doubles
%Lffor long doubles
%lufor unsigned integers or longs
%lli or %lldfor long long integers
%llufor unsigned long longs
%ofor octal representation
%nto print nothing
%%to print the % character

Example:

#include <stdio.h>
int main()
{
    printf("Hello Geek!");

    int num1 = 99;
    int num2 = 1;
    printf("The sum of %d and %d is %d\n", num1, num2, num1 + num2);

    float num = 3.14159;
    printf("The value of pi is approximately %f\n", num);

    char letter = 'a';
    printf("The letter is %c\n", letter);

    int a = 10;
    printf("Address of variable 'a' is %p", &a);

    unsigned int num = 255;
    printf("The value of num in hexadecimal is: %x\n", num);

    return 0;
}


Standard I/O Functions:

In C programming, standard I/O functions are used to read and write data from and to the standard input/output streams, which are the keyboard and the screen, respectively. 

These functions are defined in the stdio.h header file and include the following:

  • printf(): used to print formatted output to the screen
  • scanf(): used to read formatted input from the keyboard
  • getchar(): used to read a single character from the keyboard
  • putchar(): used to print a single character to the screen


1. printf() function:

The printf() function is used to print output on the screen in C programming. 

It can be used with various format specifiers to display different types of data.

This function is a part of the C standard library “stdio.h” and it can allow formatting the output in numerous ways.

Syntax:

printf(” format String”, Arguments);


Here,

  • Format String: It is a string that specifies the output. It may also contain a format specifier to print the value of any variable such as a character and an integer value like.
  • Arguments: These are the variable names corresponding to the format specifier.

Example:

int x = 7;
printf("Are you looking for your lucky number?");
printf("Your lucky number is %d", x);


//Output: 

Are you looking for your lucky number?
Your lucky number is 7


2. scanf() function:

In C programming language, scanf is a function that stands for Scan Formatted String. 

It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments.

The scanf() function is used to read input from the keyboard and can also be used with format specifiers to read different types of data. 

For example, the %d specifier is used to read integer values, while the %f specifier is used to read floating-point numbers.

  • It accepts character, string, and numeric data from the user using standard input.
  • scanf also uses format specifiers like printf.

Syntax:

The syntax of scanf() in C is similar to the syntax of printf().

int scanf( const char *format, ... );

or

scanf("format string", &argument_list);


Here,

int is the return type.

format is a string that contains the format specifiers(s).

“…” indicates that the function accepts a variable number of arguments.


Some of the commonly used format specifiers are given below.

  • %d - accept input of integers.
  • %ld - accept input of long integers
  • %lld - accept input of long long integers
  • %f - accept input of real number.
  • %c - accept input of character types.
  • %s - accepts input of a string.

Example:

int var;
scanf(“%d”, &var);

Here;

The scanf will write the value input by the user into the integer variable var.

The return value of scanf() is the number of input items successfully matched and assigned, which can be used to check if the input was successful.


3. getchar() Function:

The getchar() function is used to read a single character from the keyboard or a file. 

It returns the ASCII value of the character read. 

This function is useful when you need to read input characters from the user one by one, rather than reading an entire string at once.

The getchar() function is defined in the <stdio.h> header file. 

For example, the following code reads a character from the keyboard and prints it:

char ch;
ch = getchar();
printf("%c", ch);

The return type of getchar() is an integer, which represents the ASCII value of the character read. If the end of the file is reached, the function returns EOF.

Syntax:

char ch;
ch = getchar();

In this example, the getchar() function is called to read a single character from the standard input stream and store it in the variable ch.

Example:

Here's an example program that uses the getchar() function to read a string of characters from the user and display them on the screen:

#include <stdio.h>
int main() {
   char ch;
   printf("Enter a string of characters: ");
   while ((ch = getchar()) != '\n') {
      putchar(ch);
   }
   return 0;
}

Explanation:

In this program, the user is prompted to enter a string of characters using the printf() function. 

The getchar() function is then used inside a while loop to read each character one by one until the end of the line is reached (indicated by the '\n' character). 

The characters are then displayed on the screen using the putchar() function.

Note that the getchar() function is called inside the loop condition, not inside the loop body. 

This is because the loop needs to terminate when the end of the line is reached, and the getchar() function needs to be called at least once before the loop condition can be evaluated.


4. putchar() function:

In C programming, the putchar() function is used to write a single character to the standard output stream (usually the console) or to a file. 

This function is useful when you need to display output characters one by one, rather than displaying an entire string at once.


The putchar() function is defined in the <stdio.h> header file. It has the following syntax:

int putchar(int char);

The function takes a single argument, which represents the ASCII value of the character to be written. 

It returns the same value on success, or EOF (end-of-file) on failure.

Syntax:

The syntax for using the putchar() function is as follows:

char ch = 'a';

putchar(ch);

In this example, the putchar() function is called to write the character 'a' to the standard output stream.

Example:

Here's an example program that uses the putchar() function to display a string of characters on the screen:

#include <stdio.h>
int main() {
   char str[] = "Hello, World!";
   int i;
   for (i = 0; str[i] != '\0'; i++) {
      putchar(str[i]);
   }
   return 0;
}

Explanation:

In this program, a string of characters "Hello, World!" is stored in an array named str. 

The for loop is then used to iterate over each character in the string and display it on the screen using the putchar() function.

Note that the putchar() function can also be used with escape sequences, such as '\n' for a newline character or '\t' for a tab character. For example, the following code displays a message on two lines:

putchar('H');

putchar('i');

putchar('\n');

putchar('T');

putchar('h');

putchar('e');

putchar('r');

putchar('e');


fgetc() and getc():

The fgetc() and getc() functions are used to read a single character from a file. 

The syntax is similar to getchar(). The only difference is that these functions take a file pointer as an argument. 

The return type of these functions is also an integer, which represents the ASCII value of the character read. If the end of the file is reached, the function returns EOF.

Syntax:

int ch;
FILE *fp;
fp = fopen("file.txt", "r");
while ((ch = fgetc(fp)) != EOF) {
   putchar(ch);
}
fclose(fp);

Example:

#include <stdio.h>
int main() {
   int ch, count = 0;
   FILE *fp;
   fp = fopen("file.txt", "r");
   while ((ch = getc(fp)) != EOF) {
      if (ch == 'a') {
         count++;
      }
   }
   fclose(fp);
   printf("The file contains %d occurrences of the letter 'a'\n", count);
   return 0;
}


Note: The only difference between them is that the getc() function is implemented as a macro in the <stdio.h> header file, while the fgetc() function is implemented as a function.


getchar() vs. getc():

The getchar() function is equivalent to getc(stdin), i.e., it reads a character from the standard input. 

The getc() function can read from any file stream.


getchar() vs. getch() vs. getche():

The getch() and getche() functions are used to read a single character from the keyboard, but they do not wait for the user to press the Enter key. 

The difference between getch() and getche() is that getche() echoes the character to the screen, while getch() does not.


Return Type of getchar(), fgetc(), and getc():

The getchar() function reads a single character from the standard input. 

It returns an integer value that represents the ASCII value of the character read. 

The fgetc() and getc() functions are similar to getchar(), but they read a character from a file instead of the standard input. 

The return type of these functions is also an integer value that represents the ASCII value of the character read.


Scansets in C Programming:

Scansets, also known as character sets, are a useful feature in C programming for reading input data from the user. 

A scanset is a set of characters that can be used to match and read input data from the standard input stream. 

In this article, we will discuss the basics of scansets in C programming, including how to define and use scansets in scanf() and sscanf() functions.


Defining Scansets:

In C programming, scansets are defined using square brackets [ ] and can include a range of characters. 

Scansets can also include multiple ranges of characters, such as [a-zA-Z0-9], which matches any alphanumeric character. 

Additionally, scansets can include the ^ character at the beginning to invert the set of characters. For example, the scanset [^abc] matches any character that is not 'a', 'b', or 'c'.

For example, the scanset [abc] matches any of the characters 'a', 'b', or 'c'. Similarly, the scanset [0-9] matches any digit from 0 to 9.

Syntax:

scanf(%s[A-Z,_,a,b,c]s,str);

This will scan all the specified characters in the scanset

Example:

#include <stdio.h>
int main() {
   char str[100];
   printf("Enter a string of alphabets: ");
   scanf("%[a-zA-Z]", str);
   printf("The input string is: %s\n", str);
   return 0;
}

Explanation:

In this program, the user is prompted to enter a string of alphabets using the printf() function. 

The scanf() function is then called with a scanset notation "%[a-zA-Z]", which specifies that the input should contain only alphabets (both lowercase and uppercase). 

The input is stored in the variable str using the & operator. 

Finally, the input string is displayed on the screen using the printf() function.

 Key:  Introduction, Format Specifier, Standard I/O Functions, printf() function, scanf() function, getchar() Function:, putchar() function, Syntax:, Example, Explanation, fgetc() and getc(), getchar() vs. getc(), getchar() vs. getch() vs. getche(), Return Type, Scansets, 

إرسال تعليق

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.