Chapter 06Beginner

Input/Output in C

Make your programs interactive! Learn to display output with printf() and read user input with scanf(). Essential for every C program.

18 min readUpdated 2024-12-16
printfscanfinputoutputformat specifiers%d%f%c%s

What You Will Learn

  • Display text and numbers with printf()
  • Use format specifiers (%d, %f, %c, %s)
  • Read user input safely with scanf()
  • Format output (decimals, width, alignment)

01What is Input/Output in C?

📺 Simple Definition

Input/Output (I/O) is how your program communicates with the outside world. Input = getting data IN (from keyboard, file). Output = sending data OUT (to screen, file).

📚 The stdio.h Header

All I/O functions come from the <stdio.h> header (Standard Input/Output).

#include <stdio.h>

📖 See the complete stdio.h Reference for all functions.

FunctionPurposeType
printf()Print formatted output to screenOutput
scanf()Read formatted input from keyboardInput
getchar()Read single characterInput
putchar()Print single characterOutput
gets() / fgets()Read string (line)Input
puts()Print string with newlineOutput

02The printf() Function

📝 Syntax

printf("format string", value1, value2, ...);

The format string contains text and format specifiers (%d, %f, etc.)

📝 This program shows different ways to use printf for various data types.

printf_basic.c
C
1#include <stdio.h>
2
3int main() {
4 printf("Hello!\n"); // Text
5 printf("Age: %d\n", 25); // Integer
6 printf("Price: %.2f\n", 9.99); // Float
7 printf("Grade: %c\n", 'A'); // Character
8 printf("Name: %s\n", "Bob"); // String
9 return 0;
10}
Output

Hello!

Age: 25

Price: 9.99

Grade: A

Name: Bob

03Format Specifiers

🎯 What are Format Specifiers?

Format specifiers are placeholders that tell printf/scanf what type of data to expect and how to format it.

SpecifierData TypeExampleOutput
%d or %iint (signed)printf("%d", 42)42
%uunsigned intprintf("%u", 42)42
%ldlong intprintf("%ld", 123456789L)123456789
%lldlong long intprintf("%lld", 9999999999LL)9999999999
%ffloat / doubleprintf("%f", 3.14)3.140000
%.2ffloat (2 decimals)printf("%.2f", 3.14159)3.14
%eScientific notationprintf("%e", 12345.67)1.234567e+04
%ccharprintf("%c", 'A')A
%sstring (char array)printf("%s", "Hello")Hello
%x / %XHexadecimalprintf("%x", 255)ff
%oOctalprintf("%o", 8)10
%pPointer addressprintf("%p", &x)0x7fff...
%%Literal %printf("100%%")100%

📏 Width and Precision Modifiers

format_modifiers.c
C
1#include <stdio.h>
2
3int main() {
4 printf("[%d]\n", 42); // Normal: [42]
5 printf("[%5d]\n", 42); // Width 5: [ 42]
6 printf("[%05d]\n", 42); // Zero-pad: [00042]
7
8 printf("[%.2f]\n", 3.14159); // 2 decimals: [3.14]
9 printf("[%8.2f]\n", 3.14); // Width 8: [ 3.14]
10 return 0;
11}
Output

[42]

[ 42]

[00042]

[3.14]

[ 3.14]

04printf Variants

FunctionDescriptionUse Case
printf()Print to stdout (screen)Normal console output
fprintf()Print to file streamWrite to files, stderr
sprintf()Print to string bufferFormat string in memory
snprintf()Print to string (size limited)Safe string formatting
printf_variants.c
C
1#include <stdio.h>
2
3int main() {
4 char buf[50];
5
6 printf("Hello!\n"); // To screen
7 fprintf(stderr, "Error!\n"); // To stderr
8 sprintf(buf, "Age: %d", 25); // To string
9 printf("Buffer: %s\n", buf);
10
11 return 0;
12}
Output

Hello!

Error!

Buffer: Age: 25

💡 Always Use snprintf!

sprintf() can cause buffer overflow! Always prefer snprintf() which limits the output to your buffer size.

05The scanf() Function

📥 Understanding scanf() - Reading Input

scanf() is a function that reads formatted input from the keyboard. The name stands for "scan formatted".

int scanf(const char *format, ...);
Defined in: <stdio.h>
format: Format string with specifiers like %d, %s, %f
...: Pointers to variables where input will be stored (use & before variables!)
Returns: Number of items successfully read, or EOF (-1) on failure

📝 Usage Syntax

scanf("format string", &variable1, &variable2, ...);

⚠️ Notice the & (address-of operator) before variables!

scanf_basic.c
C
1#include <stdio.h>
2
3int main() {
4 int age;
5 char name[20];
6
7 printf("Enter age: ");
8 scanf("%d", &age); // & required!
9
10 printf("Enter name: ");
11 scanf("%s", name); // No & for arrays
12
13 printf("Hello %s, you are %d!\n", name, age);
14 return 0;
15}
Output

Enter age: 25

Enter name: Bob

Hello Bob, you are 25!

⚠️ scanf Gotchas

  • Forgot &: Causes crash or undefined behavior
  • %s stops at space: "John Doe" reads only "John"
  • Buffer overflow: %s doesn't check array size
  • Leftover newline: %c may read the newline from previous input

06scanf Variants

FunctionDescriptionUse Case
scanf()Read from stdin (keyboard)Normal user input
fscanf()Read from file streamParse file data
sscanf()Read from stringParse string data
sscanf_example.c
C
1#include <stdio.h>
2
3int main() {
4 char str[] = "Bob 25";
5 char name[20];
6 int age;
7
8 // sscanf - parse from string
9 sscanf(str, "%s %d", name, &age);
10 printf("Name: %s, Age: %d\n", name, age);
11
12 return 0;
13}
Output

Name: Bob, Age: 25

07Character and String I/O

FunctionPrototypeDescription
getcharint getchar(void)Returns next char from stdin (as int), or EOF on error
putcharint putchar(int c)Writes char c to stdout. Returns c or EOF on error
fgetschar *fgets(char *s, int n, FILE *stream)Reads at most n-1 chars into s. Safe! Use stdin for keyboard
putsint puts(const char *s)Writes string s + newline to stdout. Returns non-negative or EOF
char_io.c
C
1#include <stdio.h>
2
3int main() {
4 char ch;
5 char name[50];
6
7 // Single character
8 ch = getchar(); // Read one char
9 putchar(ch); // Print one char
10
11 // Full line (with spaces!)
12 fgets(name, 50, stdin);
13 puts(name); // Print + newline
14
15 return 0;
16}
Example

Input: A

Output: A

Input: John Doe

Output: John Doe

💡 Use fgets() Instead of scanf() for Strings!

scanf("%s", ...) stops at whitespace and can overflow buffers.
fgets() reads the entire line and is buffer-safe!

08main() with Command-Line Arguments

🎯 What are Command-Line Arguments?

Command-line arguments let you pass data to your program when you run it:

./program arg1 arg2 arg3

📝 main() Signatures

Without arguments:

int main(void)

int main()

With arguments:

int main(int argc, char *argv[])

int main(int argc, char **argv)

ParameterNameDescription
argcArgument CountNumber of arguments (including program name)
argvArgument VectorArray of strings (the actual arguments)
argv[0]Program NameAlways the name of the program
argv[1..n]User ArgumentsArguments passed by the user
main_args.c
C
1#include <stdio.h>
2
3int main(int argc, char *argv[]) {
4 printf("Arguments: %d\n", argc);
5
6 for (int i = 0; i < argc; i++) {
7 printf("argv[%d] = %s\n", i, argv[i]);
8 }
9
10 if (argc >= 2) {
11 printf("Hello, %s!\n", argv[1]);
12 }
13 return 0;
14}
$ ./program Bob

Arguments: 2

argv[0] = ./program

argv[1] = Bob

Hello, Bob!

🔧 String to Number Conversion

FunctionConverts ToExample
atoi()intatoi("42") → 42
atof()doubleatof("3.14") → 3.14
atoi_example.c
C
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(int argc, char *argv[]) {
5 if (argc >= 2) {
6 int num = atoi(argv[1]); // String to int
7 printf("Number: %d\n", num);
8 }
9 return 0;
10}
$ ./program 42

Number: 42

09Common Mistakes

❌ Forgetting & in scanf

scanf("%d", num); // Wrong!

scanf("%d", &num); // Correct!

❌ Wrong format specifier

printf("%d", 3.14); // float with %d!

printf("%f", 3.14); // Correct!

❌ Buffer overflow with %s

char s[10];

scanf("%s", s); // Dangerous!

char s[10];

scanf("%9s", s); // Safe!

❌ Newline issue with %c

scanf("%c", &ch); // Reads leftover \\n

scanf(" %c", &ch); // Space skips whitespace

❌ Not checking return value

if (scanf("%d", &num) != 1) {

printf("Invalid input!\\n");

}

10Summary

🎯 Key Takeaways

  • printf: Formatted output to screen (variants: fprintf, sprintf, snprintf)
  • scanf: Formatted input from keyboard (variants: fscanf, sscanf)
  • Format specifiers: %d (int), %f (float), %c (char), %s (string), %p (pointer)
  • fgets(): Safer than scanf for strings (handles spaces, limits size)
  • argc/argv: Access command-line arguments in main()
  • Conversion: atoi(), atof(), strtol() for string to number

12Next Steps

Now that you understand input/output in C, learn about operators to perform calculations: