Module 2: Chapter 8 — Console I/O
Console I/O in C
C does not have keywords for input/output. Instead, all I/O operations
are performed using functions defined in the
<stdio.h>
header. Console I/O refers to reading
input from the keyboard and displaying output on the screen.
Key Points:
- Console I/O uses standard input (stdin) and standard output (stdout).
- It allows reading/writing characters, strings, and formatted data.
-
<stdio.h>
must be included to use I/O functions likeprintf()
andscanf()
. - File I/O uses similar functions but interacts with files instead of the screen.
Reading and Writing Characters
The simplest form of input/output in C deals with single characters.
The functions getchar()
and putchar()
are
used for this purpose.
-
int getchar(void);
→ reads one character from the keyboard. -
int putchar(int c);
→ displays a single character on the screen. - Both return
EOF
if an error occurs. - These functions are useful in simple text processing programs.
Example:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
return 0;
}
Explanation:
-
getchar()
waits for the user to press a key and reads one character. -
putchar()
prints that character back to the screen. - EOF (End of File) can be used to stop input (Ctrl + D in Linux / Ctrl + Z in Windows).
Reading and Writing Strings
To handle multiple characters (strings), C provides
gets()
and puts()
. These are used to read
and display entire lines of text.
-
char *gets(char *str);
→ reads a string until ENTER is pressed. -
int puts(const char *str);
→ prints a string followed by a newline. - Always ensure your array has enough space to store the input string.
-
Note:
gets()
is unsafe (can cause buffer overflow); preferfgets()
.
Example:
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
gets(name); // use fgets(name, 50, stdin) instead
puts("Hello, ");
puts(name);
return 0;
}
-
gets()
reads a string until ENTER and adds a null terminator'\0'
. -
puts()
displays the string followed by a newline automatically. -
Faster and lighter than using
printf()
for string output.
Formatted Console I/O
The most commonly used I/O functions in C are
printf()
and scanf()
, which allow formatted
input and output.
-
printf()
→ displays formatted output to the screen. -
scanf()
→ reads formatted input from the keyboard. - Both belong to
<stdio.h>
. - They use format specifiers to define data types.
Example:
#include <stdio.h>
int main() {
int age;
float salary;
printf("Enter your age and salary: ");
scanf("%d %f", &age, &salary);
printf("Age: %d, Salary: %.2f\\n", age, salary);
return 0;
}
Common Format Specifiers:
%d
→ integer%f
→ float%c
→ character%s
→ string%.2f
→ floating value up to 2 decimal points
Key Notes:
-
scanf()
requires the address of variables (using&
). -
printf()
can print text and variable values together. - Always match format specifiers to variable data types.
Summary of Console I/O Functions
Function | Purpose | Defined In |
---|---|---|
getchar() |
Reads a single character from the keyboard | <stdio.h> |
putchar() |
Displays a single character on screen | <stdio.h> |
gets() |
Reads a string (unsafe, use fgets()) | <stdio.h> |
puts() |
Displays a string followed by newline | <stdio.h> |
printf() |
Formatted output | <stdio.h> |
scanf() |
Formatted input | <stdio.h> |
Formatted Console I/O
C provides two powerful standard functions for formatted input and output: printf() and scanf(). These allow the programmer to control the layout, format, and conversion of input and output data.
- printf() → Used to display formatted output on the screen.
- scanf() → Used to read formatted input from the keyboard.
-
Both are declared in the
<stdio.h>
header file and support format specifiers that determine the type and format of data.
printf( ) — Formatted Output Function
What is it?
The printf() function is used to print data to the console (standard output). It allows text and variable values to be displayed in a formatted manner according to specified conversion codes.
-
Prototype:
int printf(const char *control_string, ...);
- It returns the number of characters printed or a negative value if an error occurs.
-
The control string contains normal text and special
format specifiers (beginning with
%
) that define how data should be printed. - Each format specifier corresponds to a variable or value in the argument list.
Common Format Specifiers:
%c
→ Character%d
/%i
→ Signed decimal integer%u
→ Unsigned decimal integer%f
→ Floating-point number (decimal)%e
/%E
→ Scientific notation%o
→ Octal integer%x
/%X
→ Hexadecimal integer%s
→ String%p
→ Pointer (memory address)%%
→ Prints a literal percent sign
Example:
#include <stdio.h>
int main() {
char ch = 'A';
int num = 100;
float pi = 3.1416;
printf("Character: %c\\n", ch);
printf("Integer: %d\\n", num);
printf("Floating-point: %.2f\\n", pi);
printf("Hexadecimal: %x\\n", num);
return 0;
}
Character: A
Integer: 100
Floating-point: 3.14
Hexadecimal: 64
Format Modifiers:
-
Minimum Field Width: Specifies the minimum number
of characters to be printed. Example:
%5d
→ prints integer in a field width of 5. -
Precision Specifier: Controls number of digits
after the decimal point for floating numbers or limits string
length. Example:
%.2f
→ displays 2 digits after the decimal. -
Left/Right Alignment: Use
-
for left alignment. Example:%-10s
prints a string left-aligned in a 10-character field. -
Zero Padding: Use
0
before width for leading zeros. Example:%05d
→ 00042.
Example of Field Width & Precision:
#include <stdio.h>
int main() {
double num = 10.12345;
printf("Default: %f\\n", num);
printf("Width 10: %10f\\n", num);
printf("Precision 2: %.2f\\n", num);
printf("Zero padded: %010.2f\\n", num);
return 0;
}
Default: 10.123450
Width 10: 10.123450
Precision 2: 10.12
Zero padded: 000010.12
Key Notes:
- printf() is used for displaying text, variables, and formatted results.
- Each format specifier must match the data type of its argument.
- Incorrect format specifiers may lead to undefined behavior.
-
printf()
can also be used for debugging to display variable values.
scanf( ) — Formatted Input Function
What is it?
The scanf() function is used to read formatted input from the standard input device (keyboard). It reads different data types based on the format specifiers and stores them in corresponding variables.
-
Prototype:
int scanf(const char *control_string, ...);
- The function returns the number of items successfully read or EOF if an error occurs.
-
The control string specifies the data type to read
using
%
format codes. - Variables must be preceded by & (address-of operator) so that scanf() can store input values into them.
Common Format Specifiers:
%d
→ Reads integer (decimal)%f
→ Reads floating-point number%c
→ Reads a single character%s
→ Reads a string (stops at whitespace)%o
→ Reads octal number%x
→ Reads hexadecimal number%p
→ Reads pointer (address)
Example:
#include <stdio.h>
int main() {
int age;
float marks;
char grade;
printf("Enter age, marks, and grade: ");
scanf("%d %f %c", &age, &marks, &grade);
printf("You entered: %d, %.2f, %c\\n", age, marks,
grade);
return 0;
}
Enter age, marks, and grade: 20 85.5 A
You entered: 20, 85.50, A
Important Points:
-
Each format specifier in
scanf()
must match the variable type. -
Always use
&
before variable names (except for strings). -
%s
reads characters until a whitespace; to read full lines, usegets()
orfgets()
. -
scanf()
skips leading whitespaces but stops reading on the first space or newline for strings. - Returns the number of items successfully read — useful for error checking.
Example: Reading Strings and Numbers
#include <stdio.h>
int main() {
char name[20];
int age;
printf("Enter your name and age: ");
scanf("%s %d", name, &age);
printf("Hello %s, you are %d years old.\\n", name,
age);
return 0;
}
Enter your name and age: Alice 22
Hello Alice, you are 22 years old.
Key Notes:
-
scanf()
is useful for reading multiple values in one line. -
To avoid input issues with
%c
and%s
, clear the input buffer usinggetchar()
when mixing with numeric inputs. - Always validate user input to prevent unexpected behavior.