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
EOFif 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:%-10sprints a string left-aligned in a 10-character field. -
Zero Padding: Use
0before 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.
Guidelines / Rules for printf()
- A printf() statement always contains a format string enclosed in quotation marks.
- The control string may or may not be followed by variables or expressions whose values are to be printed.
-
Each value to be printed must have a corresponding
conversion specification (such as
%d) to hold its place in the control string. - The conversion specification determines exactly how the value will be formatted and displayed.
-
When
printf()is executed, each conversion specification is replaced by the value of its corresponding expression according to the formatting rules. -
Escape sequences like
\n(newline) and\t(tab) in the control string affect the appearance of the output but are not displayed as visible characters. - Words, blank spaces, and punctuation marks within the control string are printed exactly as they appear.
- If variables or expressions are printed, they must be separated from the control string and from each other using commas.
- Once a comma is used as a separator, adding blank spaces between arguments is not necessary (and not allowed).
Example:
printf("%d%d\\n", a, b);
printf("%d%d\\n",a,b);
Explanation: Both statements above are equivalent.
"%d%d\\n" is the control string,
\n represents the newline character, and
a and b are variables to be printed in the
order specified.
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). -
%sreads 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.
Rules to use a scanf() Function
-
Rule 1: The
scanf()function continues reading input until one of the following occurs:- The maximum number of characters has been processed,
- A whitespace character is encountered, or
- An input error is detected.
-
Rule 2: Every variable to be processed must have a
corresponding conversion specification.
The following statement will generate an error becausenum3has no format specifier:scanf("%d %d", &num1, &num2, &num3); -
Rule 3: There must be a variable address for each
conversion specification.
The following example will generate an error because no variable address is given for the third specifier:scanf("%d %d %d", &num1, &num2); - Rule 4: An error will occur if the format string ends with a whitespace character.
-
Rule 5: The input data entered by the user must
match the characters in the control string; otherwise, an error will
be generated and
scanf()will stop processing.
For example:Here, the slash (scanf("%d / %d", &num1, &num2);/) is not a whitespace or format specifier, so the user must enter data like:21/46
- Rule 6: Input data values must be separated by spaces unless otherwise specified by characters in the format string.
-
Rule 7: Any unread data value from previous input
remains in the buffer and will be considered part of the next
scanf()call. - Rule 8: When using a field width specifier, ensure it is large enough to hold the input data completely.
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
%cand%s, clear the input buffer usinggetchar()when mixing with numeric inputs. - Always validate user input to prevent unexpected behavior.
Explain Input and Output Functions in C
Input and Output functions in C are used to take data from the user
and display results on the screen. These are available in the
stdio.h library and handle character, string, and
formatted data efficiently.
Common Input Functions:
-
scanf()- Reads formatted input (numbers, characters, strings). -
gets()- Reads a line of text including spaces (deprecated in modern C). -
getchar(),getch(),getche()- Read single characters.
Common Output Functions:
-
printf()- Displays formatted output on the screen. -
puts()- Displays a string followed by a newline. -
putchar()- Prints a single character on the screen.
Reading Strings
If we declare a string as char str[100];, we can read it
in three ways:
1. Using scanf()
- Syntax:
scanf("%s", str); - No
&symbol needed for strings. - Stops reading when it encounters a space.
- Cannot read full sentences with spaces.
printf("Enter a word: ");
scanf("%s", str);
printf("You entered: %s", str);
2. Using gets()
- Syntax:
gets(str); - Reads an entire line including spaces.
-
Automatically adds a null character (
'\0') at the end. - Overcomes the limitation of
scanf().
printf("Enter a sentence: ");
gets(str);
printf("You entered: %s", str);
3. Using getchar() Repeatedly
- Reads one character at a time until a terminating character is found.
- Each character is stored in an array.
int i = 0;
char ch;
printf("Enter text (end with *): ");
ch = getchar();
while(ch != '*') {
str[i] = ch;
i++;
ch = getchar();
}
str[i] = '\0';
printf("You entered: %s", str);
Writing Strings
Strings can be displayed using three main methods:
1. Using printf()
- Syntax:
printf("%s", str); - Used to print formatted strings.
-
Supports width and precision (e.g.
printf("%5.3s", str);prints first 3 characters). -
Left justify using a minus sign (e.g.
printf("%-5.3s", str);).
printf("%s\n", str);
printf("%5.3s\n", str);
printf("%-10.4s", str);
2. Using puts()
- Syntax:
puts(str); - Automatically adds a newline after the string.
- Simpler than
printf()for plain string output.
puts(str);
3. Using putchar() Repeatedly
-
Prints each character one by one until null character
(
'\0') is reached.
int i = 0;
while(str[i] != '\0') {
putchar(str[i]);
i++;
}
Summary:
Input and output functions are essential for user interaction in C.
Functions like scanf(), printf(),
gets(), puts(), getchar(),
and putchar() make data exchange between user and
program easy and flexible.