Formatted input and output in C involve reading data from input sources (such as the keyboard or files) and writing data to output destinations (such as the screen or files) in a specified format. The printf() and scanf() functions are the primary functions used for formatted output and input, respectively. These functions allow programmers to specify the format of the data being read or written, including the data type, width, precision, and alignment. Let’s explore formatted input and output in detail:
Formatted Output with printf():
The printf() function is used to display formatted output to the standard output stream (typically the console). It takes a format string as its first argument, followed by optional additional arguments corresponding to the placeholders in the format string.
Format Specifiers:
- Format specifiers are placeholders in the format string that represent the data to be printed. Common format specifiers include:
- %d for integers
- %f for floating-point numbers
- %c for characters
- %s for strings
Example:
int num = 10; float pi = 3.14159; char ch = ‘A’; printf(“Integer: %d, Float: %f, Character: %c\n”, num, pi, ch);
Width and Precision:
- Format specifiers can be modified with width and precision specifiers to control the width and precision of the printed output.
- Example:
float num = 3.14159; printf(“Float with width and precision: %10.2f\n”, num);
Formatted Input with scanf():
The scanf() function is used to read formatted input from the standard input stream (typically the keyboard). It takes a format string as its first argument, followed by pointers to variables where the input values will be stored.
Format Specifiers:
- Format specifiers in scanf() are similar to those in printf(), but they specify the expected input format.
- Example:
int num; printf(“Enter an integer: “); scanf(“%d”, &num);
Error Handling:
- scanf() returns the number of input items successfully matched and assigned. Programmers should check this return value to handle input errors gracefully.
Other Functions for Formatted I/O:
fprintf():
- Similar to printf(), but writes formatted output to a specified output stream (e.g., a file) instead of the standard output.
sprintf():
- Similar to printf(), but writes formatted output to a string buffer instead of the standard output.
fscanf():
- Similar to scanf(), but reads formatted input from a specified input stream (e.g., a file) instead of the standard input.
Conclusion:
Formatted input and output in C provide a powerful mechanism for reading and writing data in a specific format. By using format specifiers and modifiers, programmers can control the appearance and interpretation of data, making their programs more flexible and user-friendly. Understanding how to use functions like printf() and scanf() effectively is essential for creating well-formatted input and output in C programs.