1.04

Reading Input

Learn to read data from the user. Create interactive programs that respond to user input.

Learning Objectives:

  • •Read integers and strings from standard input
  • •Process user input in different programming languages
  • •Handle multiple values on the same line
  • •Convert input strings to numbers
Prerequisites: [object Object]
Estimated Time: 45 min

Reading Input

Why Read Input?

So far, your programs have displayed hardcoded messages. But real programs are interactive — they ask for information from the user, process it, and respond.

Reading input is the bridge between static programs and dynamic ones.

Reading a Single Integer

The most common task is reading a whole number from the user.

Python

python
number = int(input("Enter a number: ")) print(f"You entered: {number}")

Breaking it down:

  • input() reads a line from the user as a string
  • int() converts the string to an integer
  • The result is stored in number

C

c
#include <stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); // %d means integer printf("You entered: %d\n", number); return 0; }

Key points:

  • scanf() reads formatted input
  • %d specifies we're reading an integer
  • &number gives the address where the value should be stored

Java

java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int number = sc.nextInt(); System.out.println("You entered: " + number); } }

C++

cpp
#include <iostream> using namespace std; int main() { int number; cout << "Enter a number: "; cin >> number; cout << "You entered: " << number << endl; return 0; }

JavaScript

In Node.js, reading synchronous input is tricky. Here's one approach:

javascript
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter a number: ', (answer) => { let number = parseInt(answer); console.log(`You entered: ${number}`); rl.close(); });

Reading a String

Often you want to read text, not just numbers.

Python

python
name = input("Enter your name: ") print(f"Hello, {name}!")

That's it! input() returns a string by default.

C

c
#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); scanf("%s", name); // %s means string printf("Hello, %s!\n", name); return 0; }

Note: scanf("%s", ...) reads until whitespace. For full lines including spaces, use fgets().

Java

java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.println("Hello, " + name + "!"); } }

Reading Multiple Values

Often you need multiple inputs.

On the Same Line

Python:

python
a, b = map(int, input("Enter two numbers: ").split()) print(f"a = {a}, b = {b}")

How it works:

  • input() reads "5 10" as a string
  • .split() breaks it into ["5", "10"]
  • map(int, ...) converts each to an integer
  • a, b = unpacks them into two variables

Java:

java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter two numbers: "); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println("a = " + a + ", b = " + b); } }

Multiple Lines

Python:

python
age = int(input("Enter your age: ")) name = input("Enter your name: ") print(f"{name} is {age} years old")

Each input() call reads a new line.

Type Conversion in Practice

When you read input, it's always a string. You must convert it:

Python

python
# String to integer age_str = input("Age: ") age = int(age_str) # String to float price_str = input("Price: ") price = float(price_str)

C

c
#include <stdio.h> #include <stdlib.h> int main() { char buffer[20]; // String to integer scanf("%s", buffer); int age = atoi(buffer); // ASCII to integer // String to float scanf("%s", buffer); float price = atof(buffer); // ASCII to float return 0; }

Java

java
String age_str = "25"; int age = Integer.parseInt(age_str); String price_str = "19.99"; double price = Double.parseDouble(price_str);

Real-World Example: Temperature Converter

Problem: Read a temperature in Celsius and convert to Fahrenheit.

Formula: F = (C × 9/5) + 32

Python:

python
celsius = float(input("Enter temperature in Celsius: ")) fahrenheit = (celsius * 9/5) + 32 print(f"{celsius}°C = {fahrenheit:.1f}°F")

Java:

java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter temperature in Celsius: "); double celsius = sc.nextDouble(); double fahrenheit = (celsius * 9/5) + 32; System.out.printf("%.1f°C = %.1f°F\n", celsius, fahrenheit); } }

C:

c
#include <stdio.h> int main() { double celsius; printf("Enter temperature in Celsius: "); scanf("%lf", &celsius); double fahrenheit = (celsius * 9/5) + 32; printf("%.1f°C = %.1f°F\n", celsius, fahrenheit); return 0; }

Key Takeaways

  • Input is always a string when received from the user
  • Use language-specific functions: input() (Python), scanf() (C), Scanner (Java), cin (C++)
  • Convert the string to the type you need: int(), float(), Integer.parseInt(), etc.
  • Multiple values can be read from one line or multiple lines
  • Format codes like %d, %s, %f specify what type you're reading

Summary

You can now read interactive input from users, making your programs respond dynamically. Combined with variables and arithmetic, you can build useful programs that solve real problems.

In the next chapter, you'll learn about conditions — the power to make decisions and execute different code based on user input.

Progress: 4/8 chapters complete in Level 1