Scanf, Printf basic and advanced

Formatted I/O in C - printf, scanf, fprintf, fscanf

Mastering I/O Functions in C: printf, scanf, fprintf, and fscanf

1. Introduction

Input and Output (I/O) operations in C connect the user to the program. Commonly used functions include printf, scanf, fprintf, and fscanf. These use format specifiers to work with variables and structured data.

2. The printf Function

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

Used to write formatted output to the screen.

Format Specifiers

FormatMeaning
%dSigned decimal int
%uUnsigned decimal
%fFloat/double
%cCharacter
%sString
%xHexadecimal
%oOctal
%%Literal %

3. The scanf Function

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

Used to read formatted input from the user.

Example

int x, y;
scanf("x=%d,y=%d", &x, &y);

Input expected: x=10,y=20. Exact formatting must match.

4. Formatting and Alignment

printf("%10d", 123);   // Right-aligned
printf("%-10d", 123);  // Left-aligned
printf("%.2f", 3.1415); // Output: 3.14

5. File I/O with fprintf and fscanf

fprintf

FILE *fp = fopen("data.txt", "w");
fprintf(fp, "x = %d, y = %.2f\n", 10, 3.14);
fclose(fp);

fscanf

int x; float y;
FILE *fp = fopen("data.txt", "r");
fscanf(fp, "x = %d, y = %f", &x, &y);
fclose(fp);

6. Data Types and Format Specifiers

Data TypeSpecifier
int%d
unsigned int%u
float%f
double%lf
char%c
char[]%s

7. Using Scanset in scanf

scanf("%[^"]", str);      // Read until newline
scanf("%[A-Za-z]", name); // Read only alphabets

8. Reading Email Address

char email[100];
scanf("%[A-Za-z0-9@._]", email);

This only allows valid characters. It does not check structure of email.

9. Unsolved Practice Problems

  • Read full address including punctuation
  • Write and read an array to file
  • Print a table of values using alignment
  • Login system using file I/O
  • Manual email structure validation
  • Date input and validation
  • Read hexadecimal and octal input
  • Handle comma-separated input
  • Store sentences to a file
  • Print padded numbers

10. Conclusion

Formatted I/O is a fundamental skill in C. By mastering printf, scanf, fprintf, and fscanf, you gain fine control over how data is read and displayed. Pay close attention to format specifiers, alignment, and data types to avoid common errors.

Post a Comment

0 Comments

Me