Standard Input and Output in C Language
Introduction
Standard Input and Output (I/O) are fundamental concepts in C programming. They allow programs to interact with the user by receiving input and providing output. In C, the standard I/O library provides functions to perform these operations efficiently.
Standard Output
Standard output refers to the display screen where the output of a program is shown. The most commonly used function for standard output in C is printf()
.
Example:
#include <stdio.h> int main() { printf("Hello, World!"); return 0; }
Hello, World!
The printf()
function can also be used to format strings with variables:
Example:
#include <stdio.h> int main() { int age = 25; printf("I am %d years old.", age); return 0; }
I am 25 years old.
Standard Input
Standard input refers to the keyboard input. The most commonly used function for standard input in C is scanf()
.
Example:
#include <stdio.h> int main() { int age; printf("Enter your age: "); scanf("%d", &age); printf("You are %d years old.", age); return 0; }
Enter your age: 25
You are 25 years old.
The scanf()
function reads formatted input from the standard input stream (keyboard).
Formatted I/O
Both printf()
and scanf()
use format specifiers to define the type of data being processed. Some common format specifiers include:
%d
- integer%f
- floating point number%c
- single character%s
- string
Error Handling in I/O
While performing I/O operations, it is important to check for errors. The printf()
and scanf()
functions return values that can be used to detect errors.
Example:
#include <stdio.h> int main() { int age; printf("Enter your age: "); if (scanf("%d", &age) != 1) { printf("Error reading input."); return 1; } printf("You are %d years old.", age); return 0; }
Enter your age: abc
Error reading input.
Conclusion
Standard Input and Output are essential parts of C programming. Understanding how to use printf()
and scanf()
effectively will help you build interactive programs. Always remember to handle errors gracefully to ensure your programs are robust and user-friendly.