Here’s an example demonstrating different input and output (I/O) operations in C, such as printf, scanf, fgets, and puts. This example takes user input in multiple ways and then displays it.
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
// Output a message with printf
printf("Enter your age: ");
// Input integer with scanf
scanf("%d", &age);
printf("Enter your height in meters (e.g., 1.75): ");
// Input floating-point number with scanf
scanf("%f", &height);
// Clear the newline character left by previous scanf
getchar();
printf("Enter your name: ");
// Input string with fgets
fgets(name, sizeof(name), stdin);
// Remove the newline character from the end of name if present
name[strcspn(name, "\n")] = '\0';
// Output using printf
printf("\nYour details:\n");
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.2f meters\n", height);
// Output using puts
puts("\nThank you for providing your information!");
return 0;
}
Explanation of I/O Operations
1. printf for Output
printfis used to display text and formatted data to the screen.- Example:
printf("Enter your age: ");outputs a prompt for the user. - Formatting codes like
%d,%f, and%sspecify the type of data being printed:%dis for integers (e.g.,age).%fis for floating-point numbers (e.g.,height).%sis for strings (e.g.,name).
2. scanf for Input
scanfreads formatted data from the user.- Example:
scanf("%d", &age);reads an integer and stores it inage. - Note the
&beforeageandheight–scanfrequires a pointer to the variable where it will store the input. - Clearing the Input Buffer: After reading with
scanf,getchar()is often used to clear any leftover newline characters, preventing issues with further input (e.g., withfgets).
3. fgets for String Input
fgetsreads a line of text (including spaces) until a newline or the specified character limit.- Example:
fgets(name, sizeof(name), stdin);reads up to 49 characters from user input intoname. fgetsdoes not require a pointer to the variable but does retain the newline at the end, so we usename[strcspn(name, "\n")] = '\0';to remove it.
4. puts for Output
putsis a simpler way to display a string with an automatic newline at the end.- Example:
puts("\nThank you for providing your information!");outputs the message without needing to specify format specifiers.
Summary of Key I/O Functions
printf: For formatted output.scanf: For formatted input, requiring pointers for variables.fgets: For reading strings with spaces; ideal for user names or sentences.puts: For printing strings, automatically appending a newline.
This example covers basic I/O functions, showing how printf, scanf, fgets, and puts can be used together to handle a variety of user input and output needs in C.
